2017-12-27 328 views
1

我有這應該創建一個新的數據庫,當用戶輸入/newdb nameofdatabase將參數傳遞給電報機器人並使用正則表達式解析?

Telegram::Bot::Client.run(token) do |bot| 
    bot.listen do |message| 
    case message.text 
    when '/newdb.*/' 
     bot.api.send_message(chat_id: message.chat.id, text: "created!, #{message.from.first_name}") 
    end 
    end 
end 

我使用正則表達式的字符串,試圖捕捉用戶的消息,事後分析它的電報機器人。 不幸的是,機器人不會給定的命令做出響應(在這種情況下,不打印"created!"行。」

我該如何去使用Ruby包裝器,捕捉用戶輸入到電報機器人?

回答

2

這是因爲/是在正則表達式元字符,這裏是一個正確的正則表達式:

Telegram::Bot::Client.run(token) do |bot| 
    bot.listen do |message| 
    case message.text 
    when /^\/newdb\s(.*)/ 
     database = $~[1] # get the database name. $~[N] regexp matches. 
     bot.api.send_message(chat_id: message.chat.id, text: "created!, #{message.from.first_name}") 
    end 
    end 
end 

%r|\A/newdb\b.*|:使用\A除非你明確地追在消息的中間回車後以及使用時%r符號FO當它包含斜槓時,r會返回正則表達式。 THX @mudasobwa

檢查正則表達式表達here

+1

'%R | \ A/NEWDB \ B * |':使用'\ A'除非你回車後明確地追在消息和使用中間'當它包含斜線時,正則表達式使用%r'表示法。另外,括號是多餘的,AFAICT。 – mudasobwa