python-3.x Discord.py :协同程序从未被期待过

plicqrtu  于 2022-12-05  发布在  Python
关注(0)|答案(1)|浏览(112)

似乎不能修复这个代码,我试图从它的邀请链接获得不和谐服务器的名称。

import discord
from discord.ext import commands

intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)

async def get_invite_name(link):
    name = await client.fetch_invite(link).guild.name
    return name

print(get_invite_name('https://discord.com/invite/veefriends'))

尝试将await放在client.fetch_invite(link).guild.name之前,但没有成功。我不了解异步。
尝试了@matthew-barlowe建议的方法,但它吐出了更多错误-

File "~/DLG/sandbox.py", line 14, in <module>
    print(asyncio.run(get_invite_name('https://discord.com/invite/veefriends')))
  File "/usr/lib/python3.10/asyncio/runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "/usr/lib/python3.10/asyncio/base_events.py", line 646, in run_until_complete
    return future.result()
  File "~/DLG/sandbox.py", line 12, in get_invite_name
    return await invite.guild.name
AttributeError: 'coroutine' object has no attribute 'guild'
sys:1: RuntimeWarning: coroutine 'Client.fetch_invite' was never awaited
ztyzrc3y

ztyzrc3y1#

您还需要等待异步 Package 函数get_invite_name。在asyncio.run(get_invite_name('https://discord.com/invite/veefriends'))中运行它将在非异步设置中处理该问题。您还需要导入asyncio

import discord
import asyncio
from discord.ext import commands

intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)

async def get_invite_name(link):
    response = await client.fetch_invite(link)
    name = response.guild.name
    return name

print(asyncio.run(get_invite_name('https://discord.com/invite/veefriends')))

如果在另一个async函数中调用它,则只需await get_invite_name('https://discord.com/invite/veefriends')就足够了

相关问题