python - 如何获取 DMChannel 对象?- 不和谐.py
问题描述
我希望机器人检查带有新表情符号的频道,然后根据新表情符号做不同的事情。它正常工作,直到表情符号在私人频道上,这使得bot.get_channel(payload.channel_id)
返回无。
我对用户或会员 ID 有同样的问题。payload.member
返回 None,但返回bot.get_user(payload.user_id)
成员对象。那么,有没有这样的东西,但有渠道?用什么来获取 DMChannel 对象?
@bot.event
async def on_raw_reaction_add(payload):
print(bot.get_channel(payload.channel_id), payload.channel_id) # This line will be deleted, it is used for showing the problem.
if payload.user_id != None:
channel = bot.get_channel(payload.channel_id)
msg = await channel.fetch_message(payload.message_id)
emoji = payload.emoji
author = payload.member
if emoji.is_custom_emoji():
emoji_count = discord.utils.get(msg.reactions, emoji=emoji).count
else:
emoji_count = discord.utils.get(msg.reactions, emoji = emoji.name).count
if payload.channel_id == channel_i:
if emoji_count > 1:
...
输出如果反应在一个DM通道,错误是因为通道是NoneType,是上一行引起的。
None 782664385889959976
Ignoring exception in on_raw_reaction_add
Traceback (most recent call last):
File "C:\Users\plays\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py",
line 312, in _run_event
await coro(*args, **kwargs)
File "C:\Users\plays\OneDrive\Рабочий стол\Python\bot2.py", line 122, in on_raw_reaction_add
msg = await channel.fetch_message(payload.message_id)
AttributeError: 'NoneType' object has no attribute 'fetch_message'
解决方案
是否有理由需要使用on_raw_reaction_add
而不是on_reaction_add
?在 99% 的情况下,后者的作用与前者相同。话虽如此,它的参数是reaction, user
[documentation]更容易解析,因为它们是 discord.py 对象。
而不是bot.get_channel
您可以检索频道,然后只需调用
channel = reaction.channel.message
完整示例:
@bot.event
async def on_reaction_add(reaction, user):
channel = reaction.message.channel
推荐阅读
- javascript - 无法呈现具有对象数组的内部数据
- ssh - "无法通过 ssh 连接到主机:权限被拒绝(公钥)。",
- winapi - 如何使用 Windows 检测“stdout”/“sterr”的 I/O 重定向
- javascript - 如何使用 JavaScript(甚至在 JQuery 的帮助下)检测或处理浏览器阻止了 URL?
- php - php正则表达式配对单词和数字
- symfony - 如何通过所有父节点的 id 获取一些子节点(DoctrineExtensions、Gedmo-Tree NestedTreeRepository、Symfony)
- python - 如何在 Django 的基于通用类的 ListView 中返回搜索词
- java - 我收到此“NullPointerException”错误
- c# - 如何使用 LINQ 表达式 ASP.NET MVC 实体框架使用外键更新多个表
- amazon-web-services - 是否可以更改 AWS cognito 托管 UI?