【问题标题】:Sending discord direct message by user ID using Python使用 Python 通过用户 ID 发送不和谐的直接消息
【发布时间】:2021-09-08 12:59:56
【问题描述】:

我制作了一个不和谐的机器人,它通过用户 ID 发送消息。
问题是我无法运行这个机器人。 代码是:

import discord
from discord.ext import commands
import json
 
bot = commands.Bot(command_prefix='?')
 
@bot.event
async def on_ready():
    print(' [!] messaging..\n')
 
    with open("ids.json", "r") as file:
        data = json.load(file)
 
    indx = 0
    for i in data:
        indx += 1
        member = await bot.fetch_user(i)
        try:
            await member.send("message to send")
            print(f" [+] Sent message {indx} / {len(data)}")
        except Exception as e:
            print(f" [!] {e}")
 
    print(" [+] Done")
 
bot.run("bot token", bot = False)

我得到的错误是:

Ignoring exception in on_ready
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "main.py", line 17, in on_ready
    member = await bot.fetch_user(i)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 1384, in fetch_user
    data = await self.http.get_user(user_id)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 250, in request
    raise NotFound(r, data)
discord.errors.NotFound: 404 Not Found (error code: 10013): Unknown User

【问题讨论】:

  • data 长什么样子?
  • 请澄清您的具体问题或提供其他详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。

标签: python python-3.x discord.py


【解决方案1】:

错误 404 表示未找到。

所以在不和谐中,错误 404 意味着找不到用户。

所以请检查您的用户 ID 并重试

【讨论】:

    【解决方案2】:

    ID 必须是整数

    with open("ids.json", "r") as file:
        data = json.load(file)
     
    indx = 0
    for i in data:
        indx += 1
        member = await bot.fetch_user(i)
        # and so on...
    

    这里的问题是 JSON 键(假设数据是一个对象,如果它是一个数组,那么只需通过删除引号将项目设为 int)只能是字符串,但 fetch_user 需要一个 int。另一件事是 fetch_user 执行 API 调用以获取用户,您应该使用 get_user 来避免向 API 发送垃圾邮件。另一件事是您应该使用enumerate 而不是创建一个变量然后在每次迭代时增加该变量

    所以重新格式化的代码是

    with open("ids.json", "r") as file:
        data = json.load(file)
     
    
    for indx, i in enumerate(data, start=1):
        indx += 1
        member = bot.get_user(int((i))
        # and so on...
    

    【讨论】:

      猜你喜欢
      • 2022-10-19
      • 2021-06-15
      • 1970-01-01
      • 2020-11-12
      • 2019-04-14
      • 2017-05-16
      • 2020-12-12
      • 2022-11-04
      • 1970-01-01
      相关资源
      最近更新 更多