[英]Discord.py Bot - How to mention random user
我正在用 Python 制作一個 Discord Bot,目前我想添加一個功能,當機器人使用命令_best
提及隨機用戶時
我試過這個代碼:
if message.content.startswith('_best'):
Channel = message.channel
randomMember = random.choice(Channel.members)
await message.channel.send(f'{randomMember.mention} is the best')
但是機器人一直在提到他自己! 有任何想法嗎?
您必須包含意圖,如下所示:
intents = discord.Intents.all()
Bot = discord.commands.Bot(intents=intents)
您必須已從Discord developer portal
啟用意圖。
最好使用此代碼:
member = random.choice(message.guild.members)
因為它包括了公會的所有用戶。
為什么不使用discord.Command
? 像這樣:
@Bot.command()
async def best(ctx):
member = random.choice(ctx.guild.members)
ctx.send(member.mention)
嘗試random.choice(message.guild.members)
而不是random.choice(Channel.members)
以獲取服務器中的成員列表
因為從文本頻道獲取隨機成員與從整個服務器獲取相同
然后嘗試message.channel.send(f'{randomMember.mention} is the best')
而且,除非您通過訪問https://discord.com/developers/applications/{your_bot's_client_id_goes_here}/bot
為您的 bot 啟用Privileged Gateway Intents並啟用Server Members Intent來制作您的 bot訪問服務器成員列表
並且還對on_message
每個命令使用@bot.command
而不是大量的 if-else 語句
代碼:
import discord
from discord.ext.commands import Bot
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot('_', intents=intents)
@bot.command()
async def best(ctx):
randomMember = random.choice(ctx.guild.members)
await ctx.send(f'{randomMember.mention} is the best')
如果上面的代碼仍然不適合你......試試這個
改變這個
@bot.event
async def on_message(message):
# do all your stuff here
進入這個
@bot.listen('on_message')
async def whatever_you_want_to_call_it(message):
# do stuff here
# do not process commands here
告訴我它是否對你不起作用...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.