繁体   English   中英

python 中的电报机器人; 自动销毁

[英]Telegram bot in python; Autodestruction

我正在尝试使用自动销毁命令配置我的机器人,这将禁止非管理员组中的每个成员。 当我在组中键入命令时,机器人不回复,只有当我直接写信给他时它才会响应,当我尝试自动销毁命令时,它会给出以下错误:

update {'update_id': 967684662, 'message': {'caption_entities': [], 'message_id': 201, 'entities': [{'type': 'bot_command', 'offset': 0, 'length': 5}], 'new_chat_photo': [], 'text': '/pyro', 'delete_chat_photo': False, 'group_chat_created': False, 'photo': [], 'channel_chat_created': False, 'supergroup_chat_created': False, 'chat': {'username': 'khagnaccio', 'first_name': 'kernel', 'id': 5377477821, 'type': 'private'}, 'date': 1661264074, 'new_chat_members': [], 'from': {'id': 5377477821, 'language_code': 'it', 'first_name': 'kernel', 'username': 'khagnaccio', 'is_bot': False}}} ha causato un errore There is no current event loop in thread 'Bot:5561807213:dispatcher'.
/home/elias/.local/lib/python3.8/site-packages/telegram/ext/dispatcher.py:575: RuntimeWarning: coroutine 'ChatMethods.get_participants' was never awaited
  self.logger.exception('An uncaught error was raised while handling the error.')
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

这是机器人代码:

import con as keys
import asyncio
from telegram.ext import *
import responses as r
from telethon import TelegramClient
from telethon.errors import SessionPasswordNeededError
from telethon.tl.functions.channels import GetParticipantsRequest
from telethon.tl.types import ChannelParticipantsSearch
from telethon.tl.types import (
    PeerChannel
)
import pyrogram
from telethon.sync import TelegramClient
from telethon.tl.functions.messages import GetDialogsRequest
from telethon.tl.types import InputPeerEmpty
import os, sys
import time

print("Iniziamo...")

def pyro_command(update, context):
    
    print('[+] scegli il gruppo dove vuoi bannare gli utenti:')
    i=0
    for g in groups:
        print('[' + str(i) + ']' + ' - '+ g.title )
        i+=1
 
    print('')
    g_index = input("inserisci il numero del gruppo scelto: ")
    target_group=groups[int(g_index)]
 
    print("Seleziono gli utenti...")
    time.sleep(1)
    all_participants = []
    all_participants = client.get_participants(target_group, aggressive=False)
    print('[+] Banno gli utenti...')
    time.sleep(1)   
    print('[+] Utenti bannati.')

def start_command(update, context):
    update.message.reply_text("INIZIALIZZAZIONE....")
    for x in range(1, 4):
        update.message.reply_text("Pyro Never Dies.")

def help_command(update, context):
    update.message.reply_text("Se hai bisogno di aiuto, chiedi a un Admin!")

def handle_message(update, context):
    text = str(update.message.text).lower()
    response = r.sample_responses(text)

    update.message.reply_text(response)

def error(update, context):
    print(f"update {update} ha causato un errore {context.error}")



try:
    api_id = "api id"
    api_hash = "api hash"
    phone = 'phone number'
    client = TelegramClient(phone, api_id, api_hash)
except KeyError:
    os.system('clear')
    print("Errore.")
client.connect()
print("Client creato e connesso....")
if not client.is_user_authorized():
    client.send_code_request(phone)
    os.system('clear')
    client.sign_in(phone, input('[+] Enter the code: '))
 
os.system('clear')

updater = Updater(keys.API_KEY, use_context = True)
dp = updater.dispatcher
dp.add_handler(CommandHandler("start", start_command))
dp.add_handler(CommandHandler("help", help_command))
dp.add_handler(CommandHandler("pyro", pyro_command))
dp.add_handler(MessageHandler(Filters.text, handle_message))
dp.add_error_handler(error)
chats = []
last_date = None
chunk_size = 900
groups=[]

result = client(GetDialogsRequest(
         offset_date=last_date,
         offset_id=0,
         offset_peer=InputPeerEmpty(),
         limit=chunk_size,
         hash = 0
     ))
chats.extend(result.chats)
for chat in chats:
    try:
        if chat.megagroup== True:
            groups.append(chat)
    except:
        continue
updater.start_polling()
updater.idle()

您必须将client.get_participants(target_group, aggressive=False)更改为await client.get_participants(target_group, aggressive=False) ,因为该方法是协程方法( async def... )。 但是,您不能在普通函数中使用await

您可以采取三个方向来完成这项工作,我将按照我认为合理的顺序列出它们:

  1. 不要混合telethonpython-telegram-bot 您显然想利用 userbot 功能,因此您必须使用telethon 但是, telethon也可用于为普通机器人编写代码,因此您实际上也不需要让 ptb 参与其中。 坚持一个框架应该会大大减少并发症的数量。
  2. 使用 PTB 的 v20.x。 在 v20(目前处于预发布模式)中,PTB 也切换到了asyncio ,因此将 PTB 和telethon结合起来应该会更容易。
  3. 管理您自己的asyncio事件循环并使用 asyncio.loop.run_until_complete 之类的东西在您在 PTB v13.x 中使用的普通回调函数中运行asyncio.loop.run_until_complete协程方法

免责声明:我目前是python-telegram-bot的维护者。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM