【问题标题】:How can I send a message to a user out of a JSON file?如何从 JSON 文件中向用户发送消息?
【发布时间】:2022-01-08 10:51:24
【问题描述】:

可能是一个很容易回答的问题,但我想在特定时间后向用户发送消息。为此,我从 JSON 中读取了他的 ID。这个有问题吗?您不能将send 附加到str,否则此错误将被吐出。

我已经尝试转换整个东西,但没有成功。有人可以在这里给我提示吗?

代码:

    @commands.Cog.listener()
    async def on_ready(self):
        period = 10 # 86400.0
        while 3:
            with open('work_data/statues.json') as j:
                u_data = json.load(j)
                for user in list(u_data.keys()): # read user, ID comes out if you do print(user)
                    if dt.datetime.now().timestamp() - u_data[user][0]['last_seen'] >= period:
                        await user.send(f"{user}, you haven't shown up at work for 24 hours and have been fired.") # part that doesn't work
                        await asyncio.sleep(2)
                        u_data.pop(user)
                        write_json(u_data)
                await asyncio.sleep(0.1)

JSON:

{
    "30288509151923XXXX": [ # Last 4 numbers removed because privacy.
        {
# rest not relevant
        }
    ]
}

错误信息:

Ignoring exception in on_ready
Traceback (most recent call last):
  File "C:\Users\Mike\PycharmProjects\MikeBot\venv\lib\site-packages\disnake\client.py", line 505, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\Mike\PycharmProjects\MikeBot\cogs\work.py", line 308, in on_ready
    await user.send(f"{user}, you haven't shown up at work for 24 hours and have been fired.")
AttributeError: 'str' object has no attribute 'send'

【问题讨论】:

  • 你没有显示完整的代码
  • @omargamal 其余代码不相关,因为只是事件不起作用。我展示了需要考虑的整个on_ready 代码。
  • 可以显示错误信息吗?
  • @FusionSid 添加错误信息,感谢指出!
  • 这能回答你的问题吗? Discord.py get user object from id/tag

标签: python discord discord.py


【解决方案1】:

我认为这是因为您无法将消息发送到需要发送给用户的号码。

代替:

await user.send(f"{user}, you haven't shown up at work for 24 hours and have been fired.")

试试:

_user = await self.client.fetch_user(int(user))
await _user.send(f"{user}, you haven't shown up at work for 24 hours and have been fired.")

【讨论】:

    【解决方案2】:

    您似乎使用的是disnake 而不是discord.py

    您可以查看他们的文档。在这里我们学习了一些关于fetch_userget_usergetch_user 的知识,它们将首先检查缓存,然后在需要时获取用户。

    在您的示例中,您可以使用以下内容:

    await self.bot.getch_user(user) # asynchronous, needs to be awaited
    

    【讨论】:

      【解决方案3】:
      user_object = await bot.fetch_user(<id>)
      await user_object.send(<message>)
      
      

      应该在你的情况下工作!

      【讨论】:

      • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
      猜你喜欢
      • 2018-07-25
      • 1970-01-01
      • 2020-11-07
      • 2023-03-30
      • 2019-06-27
      • 2018-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多