所以我有一些看起来像这样的代码:
import discord, asyncio
client = discord.Client()
@client.event
async def on_member_update(preupd, postupd):
if postupd.server.id == '1234' and postupd.permissions_in(client.get_channel('5')).read_messages == True:
embed = discord.Embed(title="Test", colour=0xFF000)
embed.add_field(name="Test", value="Test <#5>")
await client.send_message(client.get_channel('5'), embed=embed)
if postupd.server.id == '1234' and postupd.permissions_in(client.get_channel('6')).read_messages == True:
embed = discord.Embed(title="Test", colour=0xFF000)
embed.add_field(name="Test", value="Test <#6>")
await client.send_message(client.get_channel('6'), embed=embed)
if postupd.server.id == '1234' and postupd.permissions_in(client.get_channel('7')).read_messages == True:
embed = discord.Embed(title="Test", colour=0xFF000)
embed.add_field(name="Test", value="Test <#7>")
await client.send_message(client.get_channel('7'), embed=embed)
if postupd.server.id == '1234' and postupd.permissions_in(client.get_channel('8')).read_messages == True:
embed = discord.Embed(title="Test", colour=0xFF000)
embed.add_field(name="Test", value="Test <#8>")
await client.send_message(client.get_channel('8'), embed=embed)
client.run('ClientTokenHere')
正如你所看到的,我复制/粘贴了几乎相同的东西4次,但细节略有不同。所以我尝试通过制作这样的函数来缩短代码:
import discord, asyncio
client = discord.Client()
@client.event
async def on_member_update(preupd, postupd):
async def shorter(numba):
if postupd.server.id == '1234' and postupd.permissions_in(client.get_channel(str(numba))).read_messages == True:
embed = discord.Embed(title="Test", colour=0xFF000)
embed.add_field(name="Test", value="Test <#%s>" % numba)
await client.send_message(client.get_channel(str(numba)), embed=embed)
shorter('5')
shorter('6')
shorter('7')
shorter('8')
client.run('ClientTokenHere')
然而,这给了我一个错误:myfile.py:35: RuntimeWarning: coroutine 'on_member_update.<locals>.perms' was never awaited
,即使我在顶部运行“更长”的版本代码,一切运行顺利。显然我在某种程度上错误地定义了函数。我怎样才能解决这个问题?或者,还有更好的方法?感谢
答案 0 :(得分:1)
您也可以这样做:
import discord, asyncio
client = discord.Client()
@client.event
async def on_member_update(preupd, postupd):
for numba in ('5', '6', '7', '8'):
if postupd.server.id == '1234' and postupd.permissions_in(client.get_channel(str(numba))).read_messages == True:
embed = discord.Embed(title="Test", colour=0xFF000)
embed.add_field(name="Test", value="Test <#%s>" % numba)
await client.send_message(client.get_channel(str(numba)), embed=embed)
client.run('ClientTokenHere')