【问题标题】:Telegram bot replies even on random textsTelegram 机器人甚至回复随机文本
【发布时间】:2021-09-11 12:37:49
【问题描述】:

我正在创建一个 Telegram 机器人,它会以随机语言回复 Hello。工作正常,但问题是即使我随机发送一些没有意义的东西,如sfdsfjls,它也会回复。

我应该怎么做才能让它只在我说HiHello时回复,而当我随机发送一些东西时回复I don't get it

我正在使用pytelegrambotapi

我的代码:

import telebot
import random

bot_token =''

bot= telebot.TeleBot(token=bot_token)

lang1= ['Hola','Konnichiwa','Bonjour','Namaste']

# Handle normal messages
@bot.message_handler()
def send_welcome(message):

# Detect 'hi'
    if message.text == 'hi' or 'hello':
        bot.send_message(message.chat.id, (random.choice(lang1)))

【问题讨论】:

  • 嗨。请删除python-telegram-botphp-telegram-bot 的标签。前者是一个不同的 python 库,后者显然是不合适的,因为您使用的是 python。而是使用标签py-telegram-bot-api,这是您使用的库;)

标签: bots telegram telegram-bot py-telegram-bot-api


【解决方案1】:

你需要

if message.text == 'hi' or message.text == 'hello':

改为关闭

if message.text == 'hi' or 'hello':

因为or 'hello' 部分将始终 生成TRUE,就像test here 一样。


另一个选项,检查 if a string matches any other string 可能看起来像这样:

triggers = {'hi', 'hello'}
if message.text in triggers:

应用这些修复,并添加一个额外的检查 based on the comment 为我们提供以下代码:

import telebot
import random

bot_token =''

bot= telebot.TeleBot(token=bot_token)

lang1= ['Hola','Konnichiwa','Bonjour','Namaste']

# Handle normal messages
@bot.message_handler()
def send_welcome(message):

# Detect Messages
if message.text == 'hi' or message.text == 'hello':
    bot.send_message(message.chat.id, (random.choice(lang1)))
elif message.text == 'Test':
    bot.send_message(message.chat.id, 'Test succeeded')
else:
    bot.send_message(message.chat.id, 'Sorry I don\'t get it!')

【讨论】:

  • 太好了,我明白了!但是有一件事仍然没有弄清楚,我应该怎么做才能让机器人回复“对不起,我不明白!”随机输入任何内容时。
  • 请看我的编辑。使用ifelifelse 就足够了。
猜你喜欢
  • 2020-11-08
  • 2020-06-30
  • 2018-06-17
  • 2018-10-05
  • 2021-05-26
  • 1970-01-01
  • 2019-02-09
  • 2016-06-08
  • 2016-01-20
相关资源
最近更新 更多