所以基本上我正在创建Telegram Python bot。在我的本地系统里运行正常。我创建了两个不同的脚本,一个用于从一个通道获取消息,第二个用于处理该消息,并使用bot将该消息发送到另一个通道。到目前为止,一切都很顺利。问题发生后,我部署在fly.io与相同的会话名称。我尝试了很多方法和技巧。但无法解决问题。
下面是我的完整代码:
Telethon_client.py
from telethon.sync import TelegramClient, events
from celery import Celery
import os
import json
# Initialize the Celery app
app = Celery('tasks', broker=broker_url)
# Initialize the Telethon client
client = TelegramClient(session_file, api_id, api_hash)
# Set up an event handler to listen for new messages
# @client.on(events.NewMessage)
async def telethon_new_message(event):
chat_title = event.chat.title
message_text = event.message.text
if chat_title in chat_titles:
# Send a task to the Celery worker
app.send_task("tasks.handle_new_message", args=[message_text])
if __name__ == "__main__":
# Start the Telethon client
with TelegramClient(session_file, api_id, api_hash) as client:
client.start()
client.connect()
client.add_event_handler(telethon_new_message, events.NewMessage())
print("Listening for new messages...")
client.disconnect()
这是我的celery 工人
from telethon.sync import TelegramClient, events
from celery import Celery
from helper import count_non_flipkart_links_and_messages, get_amazon_product_category, find_tag, keep_tag_param, send_telegram_message, expand_short_url
import os
import asyncio
# Initialize the Celery app
app = Celery('tasks', broker=broker_url)
# Function to handle incoming messages
@app.task
def handle_new_message(message_text):
print(f"New message: {message_text}")
link_count, corresponding_messages = count_non_flipkart_links_and_messages(message_text)
updated_message = str(message_text)
for message in corresponding_messages:
current_url = expand_short_url(message)
# category, current_url = get_amazon_product_category(message)
if current_url != "":
updated_url = find_tag(current_url)
updated_message = updated_message.replace(message, keep_tag_param(updated_url))
print(updated_message)
asyncio.run(send_telegram_message(sending_channel, updated_message))
print("Message sent successfully!")
部署后,它运行顺利的一段时间,但一段时间后,他们说,由于使用相同的会话文件名在不同的ip。SQLite DB被锁定。有谁能帮帮忙吗?
Traceback (most recent call last):
File "/home/kashyap/projects/telegram-bot/telethon_client.py", line 37, in <module>
with TelegramClient(session_file, api_id, api_hash) as client:
File "/home/kashyap/.local/lib/python3.10/site-packages/telethon/client/telegrambaseclient.py", line 308, in __init__
session.set_dc(
File "/home/kashyap/.local/lib/python3.10/site-packages/telethon/sessions/sqlite.py", line 168, in set_dc
self._update_session_table()
File "/home/kashyap/.local/lib/python3.10/site-packages/telethon/sessions/sqlite.py", line 194, in _update_session_table
c.execute('delete from sessions')
sqlite3.OperationalError: database is locked
1条答案
按热度按时间6bc51xsx1#
celery 可能使用线程。Telethon使用
asyncio
。您可以将合并
asyncio
和threading
组合起来,但这并不是微不足道的。如果您不需要Celery或
threading
提供的特性,则可以直接使用asyncio
来生成所需的任务。否则,您可能应该有一个带有单个
asyncio
事件循环的专用线程,并在其中运行Telethon。然后通过例如与它通信。排队。或者你可以用
asyncio
搜索Celery来了解可以做什么。