python-3.x Discord机器人无法获取通道

am46iovg  于 2023-01-27  发布在  Python
关注(0)|答案(1)|浏览(114)

我正在尝试编写一个机器人程序,它可以同时将服务器中的新消息打印到控制台,并让用户能够同时向服务器发送消息。

import discord
from asyncio import run
from threading import Thread

intents = discord.Intents.all()
intents.members = True
client = discord.Client(intents=intents)

async def p():
  ap = await client.fetch_channel(1234567890)
  return ap

main_guild = run(p())

def log_msg(msge,date):
  with open('log.txt','a') as f:
    f.write(msge + '\n' + date)
  f.close()

async def send_a_message():
  while True:
    await main_guild.send(input('Send message: '))

@client.event
async def on_message(message):
  base_msg = str(message.author)+': '+str(message.channel.name)+': '+str(message.content)
  date = str(message.created_at)
  if len(message.attachments) == 0:
    print(base_msg)
    log_msg(base_msg,date)
    return
  for i in range(len(message.attachments)):
    base_msg += '\n'+(message.attachments[i]).url
  log_msg(base_msg,date)
  
t = Thread(target=lambda:run(send_a_message()))
t.start()

try:
  client.run('#######################')
except discord.errors.HTTPException:
  from os import system
  system('kill 1')

但是,我得到一个奇怪的错误:

Traceback (most recent call last):
  File "main.py", line 13, in <module>
    main_guild = run(p())
  File "/nix/store/hd4cc9rh83j291r5539hkf6qd8lgiikb-python3-3.10.8/lib/python3.10/asyncio/runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "/nix/store/hd4cc9rh83j291r5539hkf6qd8lgiikb-python3-3.10.8/lib/python3.10/asyncio/base_events.py", line 649, in run_until_complete
    return future.result()
  File "main.py", line 10, in p
    ap = await client.fetch_channel(999141783709679668)
  File "/home/runner/RandomRepl/venv/lib/python3.10/site-packages/discord/client.py", line 1824, in fetch_channel
    data = await self.http.get_channel(channel_id)
  File "/home/runner/RandomRepl/venv/lib/python3.10/site-packages/discord/http.py", line 604, in request
    if not self._global_over.is_set():
AttributeError: '_MissingSentinel' object has no attribute 'is_set'

是什么导致了这种情况?我该如何解决?
谢谢你。

62lalag4

62lalag41#

要获取channel,您使用的是client,但您试图在实际运行客户端之前获取通道,因此无法获取通道。
首先必须运行客户端,然后获取通道,一种可能是使用on_ready事件(在client.run('...')之后调用)来获取通道。
下面是您可以开始使用的示例代码:

import discord

client = discord.Client(intents=discord.Intents.all())
main_guild = None

@client.event
async def on_ready():
    global main_guild
    await client.wait_until_ready()
    main_guild = client.get_channel(1234567890)
    print('Connected')

@client.event
async def on_message(message):
    if message.author.id == client.user.id: return

    if message.channel.type == discord.ChannelType.private: channel = 'DM'
    else: channel = message.channel.name

    base_msg = f'{message.author}: {channel}: {message.content}'
    await main_guild.send(base_msg)

client.run('#######################')

相关问题