telegram python 匿名消息

问题描述 投票:0回答:1

我需要创建匿名消息,以便一个人可以向开发人员发送问题并由他回答。但是我有一个错误,机器人没有响应,而是根本不向用户发送消息

Мне нужно создать анонимные сообщения, чтобы человек мог отправить вопрос разработчику и он на него ответил.но у мен я ошибка, вместо ответа бот просто не отправяет сообщение пользователю

import telebot

bot = telebot.TeleBot('')
developer_chat_id = ''

@bot.message_handler(commands=['start'])
def start(message):
    bot.send_message(message.chat.id, 'Your answer.')

@bot.message_handler(func=lambda message: True)
def ask_developer(message):
    if str(message.chat.id) == developer_chat_id:
        bot.send_message(developer_chat_id, 'No you can't send a message to yourself')
    else:
        bot.send_message(developer_chat_id, f'User: {message.text}')

@bot.message_handler(func=lambda message: message.reply_to_message is not None and str(message.reply_to_message.chat.id) == developer_chat_id, content_types=['text'])
def answer_question(message):
    bot.send_message(message.reply_to_message.reply_to_message.chat.id, message.text)

bot.polling()

我预计代码是正确的,但机器人没有回答,而是写道您无法向自己发送消息

python telegram telegram-bot python-telegram-bot
1个回答
0
投票

你不能匿名

如果你想回复某个用户,你必须记住他的 ID。 这意味着您无法匿名。

现在了解为什么您总是收到您无法向自己发送消息

您的函数

answer_question
从未被调用,因为它位于处理每条短信的
ask_developer
函数下。 Telebot 将从上到下检查条件(您创建的 lambda 函数)并调用第一个函数来匹配。

要解决此问题,您应该将

answer_question
移至
ask_developer
上方。

现在为什么这行不通?

在函数

ask_developer
中,您向开发人员发送消息但没有回复。

尝试在

message.reply_to_message.reply_to_message.chat
函数中访问
answer_question
总是会抛出错误,因为
message.reply_to_message.reply_to_message
为 NONE。

如何建立反馈系统?

简单的方法是将提出问题的用户的 ID 与您的机器人发送给开发人员的消息的 ID 配对保存。

然后,当开发人员回复消息时,您可以简单地从机器人读取消息的 ID,并用它确定该消息的接收者。

要保存您从机器人收到的消息的 ID:

msg = bot.send_message(developer_chat_id, f'User: {message.text}')
msg_id = msg.id

这一切都可以通过

json
库来完成。 Json 用法:

import json

# sample dict
data = {"feedback": {"id_msg_from_bot": "id_of_user"}}

# save it to file
with open("data.json", "w") as f:
    json.dump(f)


# load it from file
with open("data.json") as f:
    d = json.load(f)

print(d)
© www.soinside.com 2019 - 2024. All rights reserved.