【问题标题】:How to send a message inside an event telethon, telegram?如何在事件电视马拉松、电报中发送消息?
【发布时间】:2022-01-01 06:22:03
【问题描述】:

我编写了一个函数,该函数在将消息写入电报频道时启动。如果消息是"start",则函数打印1,而如果收到"stop" 消息,则设置条件并导致线程中的while 循环停止。然后它应该通过 Telethon 发送消息,但我收到一个错误:

from threading import Event, Thread
from telethon import TelegramClient, sync
import telebot
condition = Event()

api_id = ******

api_hash = '*******'

client = TelegramClient('my_session', api_id, api_hash)
client.start()

# telegram bot
token_1_bot = '5******'
chat_id = -********



bot_1 = telebot.TeleBot(token_1_bot)


def do_smth():
    while not condition.is_set():
        print(1)

    client.send_message('@bots_username', 'Hi bot you are bot')
    print(2)

@bot_1.message_handler(content_types='text')
def on_message(message):
    if "start" in message.text:

        # open documents page
        # Thread(target=asyncio.run, args=(application_fill(id, channel),)).start()
        Thread(target=do_smth, args=()).start()

    elif message.text == 'stop':
        condition.set()


bot_1.infinity_polling()

我得到的错误:

Exception in thread Thread-1:
Traceback (most recent call last):
  File "C:\Python\Python37\lib\threading.py", line 917, in _bootstrap_inner
    self.run()
  File "C:\Python\Python37\lib\threading.py", line 865, in run
    self._target(*self._args, **self._kwargs)
  File "F:/aktaustroyexpert/tel_test.py", line 50, in do_smth
    client.send_message('@bot_username', 'Hi bot you are bot')
  File "C:\Python\Python37\lib\site-packages\telethon\sync.py", line 35, in syncified
    loop = asyncio.get_event_loop()
  File "C:\Python\Python37\lib\asyncio\events.py", line 644, in get_event_loop
    % threading.current_thread().name)
RuntimeError: There is no current event loop in thread 'Thread-1'.

C:\Python\Python37\lib\threading.py:951: RuntimeWarning: coroutine 'MessageMethods.send_message' was never awaited
  del exc_type, exc_value, exc_tb

怎么了?如何从一个简单的函数(收到“开始”消息时调用此函数)向机器人发送消息(通过 Telethon)?

所以我的主要任务是从打开 URL 的计算机向机器人发送 stop 消息,以使其他机器人停止打开 URL。

【问题讨论】:

    标签: python multithreading asynchronous telegram telethon


    【解决方案1】:

    await client.send_message('@bot_username', 'Hi bot you are bot')

    【讨论】:

    • 在这种情况下,我应该从 def do_smth() 中放入 async 吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-31
    • 2016-03-11
    • 2018-02-25
    • 1970-01-01
    • 2019-10-30
    • 2017-03-19
    相关资源
    最近更新 更多