You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Discord.py中如何创建赋予角色的函数并正确调用?

问题解决方法

核心问题原因

你直接用asyncio.run(test())调用函数时,Discord Bot还未完成初始化和登录流程,没有建立和Discord服务器的连接,所以bot.get_channel()无法获取到频道对象,自然无法发送消息。

正确实现方式

方式1:Bot登录后自动执行

把逻辑放到Bot的on_ready事件中,Bot成功登录后会自动触发:

import discord
from discord.ext import commands

# 初始化Bot,按需配置Intents和命令前缀
bot = commands.Bot(command_prefix='!', intents=discord.Intents.default())

async def send_test_message():
    channel = bot.get_channel(870197219192614943)
    if channel:
        await channel.send('test')
    else:
        print("无法找到指定频道")

@bot.event
async def on_ready():
    print(f'Bot已登录,账号:{bot.user}')
    await send_test_message()

# 替换为你的Bot Token
bot.run('YOUR_BOT_TOKEN')

方式2:通过命令手动触发

如果需要手动调用功能,可以创建一个自定义命令:

import discord
from discord.ext import commands

bot = commands.Bot(command_prefix='!', intents=discord.Intents.default())

@bot.command()
async def test(ctx):
    channel = bot.get_channel(870197219192614943)
    if channel:
        await channel.send('test')
        await ctx.send('消息已发送')
    else:
        await ctx.send('无法找到指定频道')

# 替换为你的Bot Token
bot.run('YOUR_BOT_TOKEN')

启动Bot后,在Discord服务器内发送!test即可触发消息发送。

关键注意事项

  • 确保Bot Token正确,且Bot已被邀请到目标服务器,拥有发送消息的权限
  • 需开启对应的Intents(如消息内容Intent,若使用命令功能),否则Bot无法正常接收事件或获取频道
  • 不要混用asyncio.run()和bot.run(),bot.run()内部已自带事件循环管理

内容的提问来源于stack exchange,提问作者Максудов Эмиль

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 01:35:22