Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
450 views
in Technique[技术] by (71.8m points)

python - How can I send a message in discord using discord.py every minute

import discord
from discord.ext import tasks

client = discord.Client()
channel = client.get_channel(CHANNEL-ID)

@tasks.loop(minutes=1)
async def test():
    await channel.send("test")

@client.event
async def on_ready():
    test.start()


TOKEN = "MYTOKEN"


client.run(TOKEN)

I got this code from Sending message every minute in discord.py, which says that it should work but I keep on getting the following error:

Unhandled exception in internal background task 'test'.
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/ext/tasks/__init__.py", line 101, in _loop
    await self.coro(*args, **kwargs)
  File "/Users/me/Coding/Py/Gmail/bot.py", line 9, in test
    await channel.send("test")
AttributeError: 'NoneType' object has no attribute 'send'

What can I do to fix this?

question from:https://stackoverflow.com/questions/65540870/how-can-i-send-a-message-in-discord-using-discord-py-every-minute

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You're getting None because the client's cache isn't loaded in yet.

I'd also recommend using commands.Bot(...) as opposed to discord.Client() if you're planning on adding commands later. commands.Bot() inherits Client(), so anything you can do right now, you'll also be able to do with Bot().

To fix this, you can get the user in the on_ready event:

@tasks.loop(minutes=1)
async def test(channel):
    await channel.send("test")

@bot.event
async def on_ready()
    channel = bot.get_channel(ID_HERE)
    test.start(channel=channel)

If you're still getting None, you need to enable privileged intents. This can be done by the following code, and enabling the following button in your application page:

intents = discord.Intents().all()

bot = commands.Bot(command_prefix=..., intents=intents)

enter image description here


References:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...