[英]How to send a message with discord.py without a command
import discord
import asyncio
client = discord.Client()
@client.event
async def on_ready():
print("I'm ready.")
async def send(message):
await client.send_message(client.get_channel("412678093006831617"), message)
client.run("token")
loop = asyncio.get_event_loop()
loop.run_until_complete(send("hello"))
嗨,我想制作一個GUI。 當有人輸入他的名字並按“確定”時,我的不和諧機器人應發送一條消息。 基本上我以為我用它的名字叫異步,沒有用。 然后我做了一個事件循環。 與print()一起工作,但是機器人沒有發送消息,所以我認為它還沒有准備好,當我把wait_until_ready()放到那里時,它什么也不執行,所以我認為我必須把client.run(“ token “)在事件循環之前也無效。
你們可以幫我嗎? :)
您的代碼無法正常工作的原因是client.run
被阻止,這意味着它將不執行任何操作。 這意味着您的loop
將永遠無法實現。
要解決此問題,請使用client.loop.create_task
。
GitHub的discord.py
有一個后台任務,發現的例子在這里 。 您應該可以將此用作參考。 當前,該任務每分鍾都會在給定頻道上發布一條消息,但是您可以輕松地對其進行修改以等待特定操作。
import discord
import asyncio
client = discord.Client()
async def my_background_task():
await client.wait_until_ready()
counter = 0
channel = discord.Object(id='channel_id_here')
while not client.is_closed:
counter += 1
await client.send_message(channel, counter)
await asyncio.sleep(60) # task runs every 60 seconds
@client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('------')
client.loop.create_task(my_background_task())
client.run('token')
對於敏感的行為,你有兩個選擇:你可以寫一個on_message
事件處理程序,或使用discord.ext.commands
模塊。 我建議使用commands
,因為它功能更強大,並且不會將所有內容都放在一個協程中。
from discord.ext.commands import Bot
bot = Bot(command_prefix='!')
@bot.event
async def on_ready():
print("I'm ready.")
global target_channel
target_channel = bot.get_channel("412678093006831617")
@bot.command()
async def send(*, message)
global target_channel
await bot.send_message(channel, message)
將用!send Some message
來調用。 *, message
語法只是告訴該漫游器不要嘗試進一步解析消息內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.