同步命令执行的问题

问题描述 投票:0回答:1

这是一个代码示例:

import vk_api
from vk_api.longpoll import VkEventType, VkLongPoll
import discord
from discord.ext import commands
import asyncio

client = commands.Bot(command_prefix='!', intents=discord.Intents.all())

@client.event
async def on_ready():
    print('The bot is connected to Discord!')

@client.event
async def on_message(message):
    if message.author == client.user:  
        return
    await client.process_commands(message)

@client.command(pass_context=True)
async def hi(ctx: commands.Context):
    await ctx.send('Hi!')

login = 'login'
password = 'password'
api_version = 'api'
chat_id = 1

vk_session = vk_api.VkApi(login, password, app_id=api_version)
vk_session.auth()

vk = vk_session.get_api()

longpoll = VkLongPoll(vk_session)
async def disbot():
    for event in longpoll.listen():
        if event.type == VkEventType.MESSAGE_NEW and event.from_chat and event.chat_id == chat_id:
            user_id = event.user_id
            message = event.text
            attachments = event.attachments
            user_info = vk.users.get(user_ids=user_id)
            user_name = user_info[0]['first_name'] + ' ' + user_info[0]['last_name']
            await client.wait_until_ready()
            channel = client.get_channel(id)
            if '@all' in message:
                if 'attach1_type' in attachments:
                    await channel.send(f"{user_name} » {message} [Attachment] @everyone")
                else:
                    await channel.send(f"{user_name} » {message} @everyone")
            else:
                if 'attach1_type' in attachments:
                    await channel.send(f"{user_name} » {message} [Attachment]")
                else:
                    await channel.send(f"{user_name} » {message}")

async def main():
    async with client:
        client.loop.create_task(disbot())
        await client.start('Token')

asyncio.run(main())

我创建了一个discord 机器人,将消息从VK 聊天转发到discord,并决定向其中添加几个命令。问题是,当我运行机器人时,它只转发消息,忽略任何命令。

我强迫机器人响应命令,但它不转发消息。如果他们告诉我如何让机器人同时做所有事情,我会很高兴。

python discord.py bots python-asyncio vk
1个回答
0
投票

您已经发现了异步程序中阻塞代码的烦恼。

for event in longpoll.listen():
行正在阻塞您的事件循环 - 它不会让您的任何其他代码运行。

阻塞代码就是阻塞代码,即使你把它放在一个任务中,所以你最好的选择是找到一个使用异步主体的异步

vk_api
库替代品,快速谷歌搜索显示了这个。用所述异步库替换当前函数可能如下所示:

import vkreal
import asyncio
import discord
from discord.ext import commands

client = commands.Bot(command_prefix='!', intents=discord.Intents.all())

# ... command definitions here

token = "Your token"
session = vkreal.VkApi(token = token)
vk = session.api_context()
longpoll = vkreal.VkLongPoll(session, loop = loop)

async def longpoll_listener():
    async for event in longpoll.listen():
        print(event['type']) 
        ... # Remaining code here

async def main():
    async with client:
        client.loop.create_task(longpoll_listener())
        await client.start('[BOT TOKEN]')

asyncio.run(main())

此示例的代码是在 vkreal 存储库测试中找到的,我建议您查看其源代码和文档以了解如何完成实现。祝你好运!

© www.soinside.com 2019 - 2024. All rights reserved.