bots - 电报机器人无法发送直接消息
问题描述
我正在使用pytelegrambotapi
. 但是当我测试代码时,我的 Telegram Bot 总是回复这样引用我的输入,我不希望它引用我的输入消息,而是直接发送消息。
另外,我怎样才能通过使用简单Hi
或Hello
不使用/hi
或/hello
.
我的代码:
import telebot
import time
bot_token = ''
bot= telebot.TeleBot(token=bot_token)
@bot.message_handler(commands=['start'])
def send_welcome(message):
bot.reply_to(message, 'Hi')
@bot.message_handler(commands=['help'])
def send_welcome(message):
bot.reply_to(message, 'Read my description')
while True:
try:
bot.polling()
except Exception:
time.sleep(10)
解决方案
我不希望它引用我的输入消息,而是直接发送消息。
bot.reply_to
回复消息本身。如果您想发送单独的消息,请使用bot.send_message
. 您需要传递您希望向其发送消息的用户的 ID。您可以在上面找到此 ID,message.chat.id
以便将消息发送到同一个聊天室。
@bot.message_handler(commands=['help'])
def send_welcome(message):
# Reply to message
bot.reply_to(message, 'This is a reply')
# Send message to person
bot.send_message(message.chat.id, 'This is a seperate message')
另外,如何仅使用简单的 Hi 或 Hello 而不是 /hi 或 /hello 来获得回复。
代替使用 a message_handler
,commands=['help']
您可以删除参数以捕获任何命令消息处理程序未捕获的每条消息。
上面实现的示例:
import telebot
bot_token = '12345'
bot = telebot.TeleBot(token=bot_token)
# Handle /help
@bot.message_handler(commands=['help'])
def send_welcome(message):
# Reply to message
bot.reply_to(message, 'This is a reply')
# Send message to person
bot.send_message(message.chat.id, 'This is a seperate message')
# Handle normal messages
@bot.message_handler()
def send_normal(message):
# Detect 'hi'
if message.text == 'hi':
bot.send_message(message.chat.id, 'Reply on hi')
# Detect 'help'
if message.text == 'help':
bot.send_message(message.chat.id, 'Reply on help')
bot.polling()
推荐阅读
- dask - 控制在调度程序中加载块的平局选择?
- angular - Angular 5 路由 - 标题和导航栏路由问题
- html - 如何在两个并排图像上重叠文本
- out-of-memory - Opennlp OutOfMemoryError:具有 16GB RAM 的 Java 堆空间
- c# - 如何关闭表单并重新打开它?
- unity3d - 新场景下的 Unity 调用方法
- javascript - jQuery对话框不能第二次调用
- python - 使用 Python Pandas 按不同字符对字符串进行切片
- python - 在 Windows 上安装 simplecrypto 时出错
- javascript - 使用 .call() 的 JavaScript 继承