所以,我需要我的机器人转发聊天消息。但是为了做到这一点,我需要获取我想要转发的消息的 id(这是一条旧消息)。如何获取该消息的 id 以便我可以发送它?
这是我正在使用的代码
@bot.message_handler(func=lambda m: True)
def reply_ids(message):
cid = message.chat.id
bot.reply_to(message, "The message id is: " + str(message.message_id) + " This chat ID is: " + str(cid))
Run Code Online (Sandbox Code Playgroud) 我一直在使用Telegram机器人使用python的telebot库从台式计算机向我发送不同的通知。一切工作了很长时间,但是有一天它停止了工作。
这是代码(Python 2.7):
import telebot
import socket
TELEBOT_TOKEN = '<token>'
CHAT_ID = <chat id>
bot = telebot.TeleBot(TELEBOT_TOKEN)
def notify(message):
bot.send_message(CHAT_ID, 'Notification from ' + socket.gethostname() + ':\n' + message)
notify('Hello world!')
Run Code Online (Sandbox Code Playgroud)
当我尝试在解释器中执行此操作时,得到以下信息:
Python 2.7.12 (default, Nov 19 2016, 06:48:10)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import telebot
>>> TELEBOT_TOKEN = '<token>'
>>> CHAT_ID = <chat id>
>>> bot = telebot.TeleBot(TELEBOT_TOKEN)
>>> bot.send_message(CHAT_ID, 'Hello world!')
{'ok': False, 'error': 'Got unexpected response. (404) …Run Code Online (Sandbox Code Playgroud) 有一个电报群,里面有40000多个共享文件。
是否有任何机器人可以一次下载所有这些?如果没有,是否有任何使用python下载共享媒体文件的电报api脚本方法?
在我的代码中,我面临callbackquery处理程序的问题,当我点击/start命令Next按钮出现时,当我点击该按钮时,它给我回复hi,直到此输出正确为止。然后当我点击另一个命令/help然后帮助按钮出现时,当我点击那个帮助按钮然后它给我相同的答复 next button is hi。
结论:有没有办法杀死旧的callbackquery处理程序。我发现方法是Conversationhandler.END从callbackquery处理程序函数返回,但它限制了我在谷歌上搜索的功能,但没有找到预期的输出。
这是我的代码:
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Updater, CommandHandler, CallbackQueryHandler, ConversationHandler
TELEGRAM_HTTP_API_TOKEN = 'token'
FIRST, SECOND, HELP = range(3)
def start(bot, update):
keyboard = [
[InlineKeyboardButton(u"Next", callback_data=str(FIRST))]
]
reply_markup = InlineKeyboardMarkup(keyboard)
update.message.reply_text(
u"Start handler, Press next",
reply_markup=reply_markup
)
return FIRST
def first(bot, update):
query = update.callback_query
#reply_markup = InlineKeyboardMarkup(keyboard)
bot.send_message(chat_id=query.message.chat_id, …Run Code Online (Sandbox Code Playgroud) 我一直在尝试创建一个电报机器人。我用 Python 编码,以下是我到目前为止所做的。
import logging
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Updater, CommandHandler, CallbackQueryHandler
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger(__name__)
@app.route("/")
def start(bot, update):
help_text = 'text'
keyboard = [[InlineKeyboardButton("Button_1", url=('url'))]]
reply_markup = InlineKeyboardMarkup(keyboard)
update.message.reply_text(help_text, reply_markup=reply_markup)
def button(bot, update):
query = update.callback_query
bot.edit_message_text(text="Selected option: {}".format(query.data),
chat_id=query.message.chat_id,
message_id=query.message.message_id)
def error(bot, update, error):
logger.warning('Update "%s" caused error "%s"', update, error)
def main():
updater = Updater(<TOKEN>)
updater.dispatcher.add_handler(CommandHandler('start', start))
updater.dispatcher.add_handler(CallbackQueryHandler(button))
updater.dispatcher.add_error_handler(error)
updater.start_polling()
updater.idle()
if __name__ == "__main__": …Run Code Online (Sandbox Code Playgroud) 我正在使用 Telethon 的send_message函数向各种聊天发送消息。
有时,目的地是另一个用户(只是一个聊天中的普通用户),有时是一个组,有时是一个超级组,有时是一个频道(我是其中的管理员)。
如果我理解正确,语法应该是:
client.send_message(entity,text)
但我无法弄清楚entity在不同情况下参数应该是什么。我发现特别令人困惑的是指定整数 id 似乎对某些组有效,但对其他组无效。
例如:
我与拥有 user_id 的11111人以及另一个拥有 user_id 的人进行了正常的一对一聊天22222。
此外,我分为两个组(实际上是超级组),它们具有 channel_id33333和44444.
我可以指定11111或33333作为实体,并且消息被正确发送(分别发送给第一个人或第一组)。但是,如果我指定22222or 44444,则会出现错误:
找不到对应于“{}”'的任何实体。格式(字符串)
ValueError:找不到对应于“22222”的任何实体
我还使用同一个 Telethon 实例从所有 4 个聊天中收到消息,并且一切正常。
所以我的问题是:如何为 send_message() 获取正确的实体数据?
我们正在为电报机器人使用 python API,并且需要能够识别用户。
连接机器人的每个用户的 chat_id 是否唯一?
我们可以相信 chat_id 是一致的吗?例如,相同的chat_id 会告诉我们这是同一个用户,并且每个与bot 连接的用户都会有一个在会话之间保持一致的chat_id?
谢谢
python authentication telegram python-telegram-bot telegram-bot
语境:
我正在使用PyTelegramBotAPi或Python Telegram Bot
当用户开始对话时,我正在运行一个代码。
当用户开始对话时,我需要向他发送第一张图片和一个问题他是否看到图片中的东西,该函数需要等待用户输入并返回他是否看到它。
之后,我将需要继续循环发送图片并等待答案并对其运行二分算法。
到目前为止我尝试过的:
我尝试使用等待响应的回复标记或带有处理程序的内联键盘,但我被卡住了,因为我的代码正在运行而没有等待用户输入。
编码:
@bot.message_handler(func=lambda msg: msg in ['Yes', 'No'])
@bot.message_handler(commands=['start', 'help'])
def main(message):
"""
This is my main function
"""
chat_id = message.chat.id
try:
reply_answer = message.reply_to_message.text
except AttributeError:
reply_answer = '0'
# TODO : should wait for the answer asynchnonossly
def tester(n, reply_answer):
"""
Displays the current candidate to the user and asks them to
check if they see wildfire damages.
"""
print('call......')
bisector.index = n
bot.send_photo(
chat_id=chat_id,
photo=bisector.image.save_image(), …Run Code Online (Sandbox Code Playgroud) 我想创建一个 Telegram 机器人来检查网站上是否有新帖子(目前出于测试目的每 15 秒检查一次)。如果是这样,它应该将包含帖子内容的消息发送到 Telegram 频道。
为此,我已经有了以下“代码骨架”:(格式化和添加方面的精细工作稍后进行)
import requests
import asyncio
from bs4 import BeautifulSoup
from telegram import InputMediaPhoto
from telegram.ext import Updater
# Telegram Bot API Token
API_TOKEN = 'XXXXXXXXXXXXXXXXX'
# URL of the website
URL = 'https://chemiehalle.de'
# List for storing seen posts
seen_posts = []
# Function for fetching posts
def get_posts():
# Send request to the website
res = requests.get(URL)
# Parse HTML content
soup = BeautifulSoup(res.content, 'html.parser')
# Find all posts on the website …Run Code Online (Sandbox Code Playgroud) 我希望我的 FastAPI 应用程序能够访问始终实际bot_data的python-telegram-bot。我需要这个,所以当我调用 FastAPI 中的某个端点时,可以将消息发送到所有聊天,存储在bot_data.
据我了解这个问题:bot.run_polling()并uvicorn.run(...)启动两个独立的异步循环。我需要将它们整合在一起运行。
UPD-1:
感谢@MatsLindh,我创建了下一个函数,我将其传递给主块,但它的工作不一致。有时bot.run_polling()(获得正确的循环并且一切正常,但其他时候并因存在不同循环的错误而中断):
import asyncio
from uvicorn import Config, Server
# --snip--
def run(app: FastAPI, bot:Application):
# using get_event_loop leads to:
# RuntimeError: Cannot close a running event loop
# I guess it is because bot.run_polling()
# calls loop.run_until_complete() different tasks
# loop = asyncio.get_event_loop()
loop = asyncio.new_event_loop()
server = Server(Config(app=app, port=9001))
loop.create_task(server.serve())
t = Thread(target=loop.run_forever)
t.start()
bot.run_polling()
t.join() …Run Code Online (Sandbox Code Playgroud) python-3.x python-asyncio telegram python-telegram-bot fastapi
python ×7
telegram ×7
telegram-bot ×7
python-3.x ×3
entity ×1
fastapi ×1
python-2.7 ×1
telethon ×1