尝试使用discord.py制作Discord机器人,但出现错误 [英] Trying to make a Discord bot with discord.py, getting errors

查看:72
本文介绍了尝试使用discord.py制作Discord机器人,但出现错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试让机器人每隔几秒钟从一组预定义的消息中发送一条消息.

I'm trying to get the bot to send a message every few seconds from a set of predefined messages.

import discord
import asyncio
import random

client = discord.Client()

async def background_loop():
    await client.wait_until_ready()
    while not client.is_closed:
        channel = client.get_channel("channel id here")
        messages = ["Hello!", "How are you doing?", "Howdy!"]
        await client.send_message(channel, random.choice(messages))
        await asyncio.sleep(120)

client.loop.create_task(background_loop())
client.run("discord token here")

但是当我尝试运行它时,我在控制台中收到此错误,并且没有消息发送到聊天室中.

But when i try too run it, i get this error in the console and no messages are sent into the chat.

/usr/bin/python3.5 /root/PycharmProjects/untitled/Loop.py
Task exception was never retrieved
future: <Task finished coro=<background_loop() done, defined at /root/PycharmProjects/untitled/Loop.py:8> exception=InvalidArgument('Destination must be Channel, PrivateChannel, User, or Object. Received NoneType',)>
Traceback (most recent call last):
  File "/usr/lib/python3.5/asyncio/tasks.py", line 239, in _step
    result = coro.send(None)
  File "/root/PycharmProjects/untitled/Loop.py", line 13, in background_loop
    await client.send_message(channel, random.choice(messages))
  File "/usr/local/lib/python3.5/dist-packages/discord/client.py", line 1145, in send_message
    channel_id, guild_id = yield from self._resolve_destination(destination)
  File "/usr/local/lib/python3.5/dist-packages/discord/client.py", line 289, in _resolve_destination
    raise InvalidArgument(fmt.format(destination))
discord.errors.InvalidArgument: Destination must be Channel, PrivateChannel, User, or Object. Received NoneType

推荐答案

我通过编写帮助程序函数从客户端获取Channel对象的方法解决了此问题

I fixed this by writing a helper function to get the Channel object from the client

def get_channel(channels, channel_name):
    for channel in client.get_all_channels():
        print(channel)
        if channel.name == channel_name:
            return channel
    return None

client = discord.Client()
general_channel = get_channel(client.get_all_channels(), 'general')
await client.send_message(general_channel, 'test msg')

这篇关于尝试使用discord.py制作Discord机器人,但出现错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆