【问题标题】:Discord.py on_message() but only for private messagesDiscord.py on_message() 但仅用于私人消息
【发布时间】:2020-09-16 09:21:11
【问题描述】:

所以,我正在开发一个不和谐的机器人。并且正在使用 on_message() 事件,该事件适用于私人消息和服务器。我希望这只能在私人消息中使用,并且不确定如何去做。 如果有人可以帮助我,那就太好了。

import os
import discord
from discord.ext import commands


TOKEN = ''
quotedUsers = []

client = commands.Bot(command_prefix = '/')

@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')
    await client.change_presence(activity=discord.Game(name='with myself.'))
    
@client.event
async def on_message(message):
    await message.author.send("Recieved: " + message.content)

@client.command()
async def search(ctx, *, question):
    await ctx.author.send("Searching: " + question)
    

client.run(TOKEN)

【问题讨论】:

  • 您刚刚发布了您的机器人令牌。您需要尽快重新生成它。
  • @JoshuaNixon Discord 已开始自动获取泄露的令牌并为您自动重新生成 - 您还会收到来自他们的 DM
  • 哎呀,我太傻了。现在修好了。 :O

标签: python bots discord discord.py


【解决方案1】:

群组 DM 中也不存在消息公会,因此您必须检查您发送消息的频道是否为 DM。您可以使用用户的dm_channel 属性:

@client.event
async def on_message(message):
    if message.channel.id == message.author.dm_channel.id: # dm only
        # do stuff here #
    elif not message.guild: # group dm only
        # do stuff here #
    else: # server text channel
        # do stuff here #

【讨论】:

    【解决方案2】:

    收到 DM 后,它不会有公会,因此您可以像这样使用该逻辑:

    @client.event
    async def on_message(message):
        # you'll need this because you're also using cmd decorators
        await client.process_commands(message)
        if not message.guild:
            await message.author.send(f"Received: {message.content}")
    

    参考资料:

    【讨论】:

      【解决方案3】:

      您好,我发现虽然在玩游戏时,discord 将消息作为 python 中的 dm 发送给机器人,这将使用 discord.channel.DMChannel 来完成,如果消息是在文本通道 discord.channel.TextChannel 中完成的。

      我已经通过在对象上放置一个类型函数来查看消息侦听器中发生的情况来证明这一点。

      isinstance(message.channel, DMChannel)
      

      【讨论】:

        猜你喜欢
        • 2018-09-19
        • 1970-01-01
        • 2020-11-27
        • 1970-01-01
        • 1970-01-01
        • 2022-07-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多