Я написал следующий код, который в идеале способен выполнять и «прослушивать» новые сообщения, поступающие с указанным идентификатором чата.
Я заметил, что он ничего не делает, несмотря на новые сообщения отображаются в идентификаторе чата. Кто-нибудь знает, чего не хватает, чтобы это работало? Я дважды проверил токен бота от BotFather (который по соображениям безопасности я удалил).
Некоторое время исследовал, пока не решил опубликовать здесь, чтобы получить помощь. Для дополнительного контекста, моя цель состоит в том, чтобы при появлении нового сообщения текст печатался, а также сохранялся в файл JSON.
import json
import asyncio
import time
from telegram import Bot
from telegram.error import TelegramError
import nest_asyncio
nest_asyncio.apply()
om_private_alerts_channel_id = ''
bot_token = 'sample:sample' # from BotFather
# Function to process messages
def process_message(message):
text = message.text
entities = message.entities
# Print message details to console
print(text)
print(entities)
# Save message details to log.json
log_entry = {
"text": text,
"entities": entities
}
with open('log.json', 'a') as file:
file.write(json.dumps(log_entry) + '\n')
# Async function to receive messages
async def receive_messages(bot):
last_update_id = None
while True:
try:
updates = await bot.get_updates(
offset=last_update_id, timeout=30, allowed_updates=[])
if updates:
last_update_id = updates[-1].update_id + 1
for update in updates:
message = update.channel_post
if message:
if str(message.chat.id) == om_private_alerts_channel_id:
process_message(message)
except TelegramError as e:
print("Error receiving messages:", e)
await asyncio.sleep(1)
# Main async function
async def main():
bot = Bot(bot_token)
try:
# Start receiving messages asynchronously
await receive_messages(bot)
except KeyboardInterrupt:
print("Bot stopped.")
if __name__ == "__main__":
asyncio.run(main())
Подробнее здесь: https://stackoverflow.com/questions/786 ... ith-python