0

I'm trying to stop bot execution. But i can't do it. When i write in the telegram bot command /stop, that he must stop. Code:

# -*- coding: utf-8 -*-
import telebot
import asyncio
from telethon import TelegramClient,sync,events,utils
from telethon.events import StopPropagation

api_id = ***
api_hash = '******'
username = '*****'
id_channel = -*** 
token = '*****'

bot = telebot.TeleBot(token)
client = TelegramClient(username, api_id, api_hash)

@bot.message_handler(commands=['start','stop'])
def start(message):
    if '/start' in message.text:
        handler_state(True)
        string = f'<b>Привет {message.from_user.first_name}!</b>\nВведите канал для парсинга и свой канал.\n<i>Пример: <pre>channel_pars,your_channel</pre></i>'
        bot.send_message(message.chat.id, string, parse_mode='html')
    elif '/stop' in message.text:
        string = '<b>Парсер остановлен!</b>'
        bot.send_message(message.chat.id, string, parse_mode='html')
        handler_state(False)

def handler_channel(my_channel,parse_channel,stop_script='start'):
    @client.on(events.NewMessage(chats=(parse_channel)))
    async def normal_handler(event):
        if 'stop' in stop_script:
            await client.disconnect()
        #print(event.message.file.media)  # картинка
        message = event.message.to_dict()['message']
        send_data(message)

    client.start()
    client.run_until_disconnected()


def send_data(message):
    bot = telebot.TeleBot(token)
    bot.send_message(id_channel,message)

def handler_state(state):
    if not state:
        handler_channel('default','default','stop')

    my_channel = None
    parse_channel = None
    @bot.message_handler(content_types=['text'])
    def send_message(message):
        if state:
            if ',' not in message.text:
                return bot.send_message(message.chat.id,'<b>Проверьте правильность ввода!</b>',parse_mode='html')
            channels = message.text.split(',')
            my_channel = channels[-1]
            parse_channel = channels[0]
            if not my_channel or not parse_channel:
                return bot.send_message(message.chat.id,'<b>Проверьте правильность ввода!</b>',parse_mode='html')

            bot.send_message(message.chat.id,f'Введенные данные: <pre>{parse_channel},{my_channel}</pre> \n <b>Парсим</b>',parse_mode='html')


        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        if state:
            handler_channel(my_channel,parse_channel)


bot.polling(none_stop=True)

Here is the error that occurs:

p1.py:36: RuntimeWarning: coroutine 'AuthMethods._start' was never awaited
  client.start()
p1.py:37: RuntimeWarning: coroutine 'UpdateMethods._run_until_disconnected' was never awaited
  client.run_until_disconnected()
egvo
  • 1,493
  • 18
  • 26
Евгений
  • 123
  • 1
  • 5

1 Answers1

1

Similar to how you start Telethon with client.connect() (or a variant, like start or using a with block), you would stop it with client.disconnect().

But your issue seems different.

You seem to be using telebot, which is a threaded library. Using threading and asyncio together requires special care and a deeper understanding on how both libraries work. While How to combine python asyncio with threads? may help, I'd recommend replacing telebot with an asynchronous bot library (such as Telethon itself, and then you would only need to worry about one library).

Lonami
  • 5,945
  • 2
  • 20
  • 38