嗨,我正在尝试制作一个投票机器人,但我在这里遇到了一个问题是代码忽略了除 + poll 之外的其他命令
import discord
import os
import requests
import json
import random
pollid = 0
emoji1 = '\N{THUMBS UP SIGN}'
emoji2 = '\N{THUMBS DOWN SIGN}'
client = discord.Client()
sad_words=["sad","depressed", "unhappy","angry","miserable","depressing"]
starter_encouragements = ["Cheer up", "hang in there.", "You are a great person / bot!"]
def get_quote():
response = requests.get("https://zenquotes.io/api/random")
json_data = json.loads(response.text)
quote = json_data[0]['q'] + " -" + json_data[0]['a']
return[quote]
from discord.utils import get
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
global pollid
#if message.author == client.user:
# return
msg = message.content
if message.content.startswith('+encourage'):
quote=get_quote()
await message.channel.send(quote)
if any(word in msg for word in sad_words):
await message.channel.send(random.choice(starter_encouragements))
if message.content.startswith("+joke"):
from dadjokes import Dadjoke
dadjoke = Dadjoke()
await message.channel.send(dadjoke.joke)
if message.content.startswith("+poll"):
pollid = pollid+1
await message.channel.send(content = msg.split(' ', 1)[1] + ' (number of polls made ' + str(pollid) + ')')
if message.author == client.user:
await message.add_reaction(emoji1)
await message.add_reaction(emoji2)
reaction = get(message.reactions, emoji=emoji1)
#reaction2 = get(message.reactions, emoji=emoji2)
#if (reaction != None and reaction2 != None):
# totalcount = reaction.count + reaction2.count
#if totalcount>=2:
if (reaction != None and reaction.count != 1):
await message.channel.send('The outcome of the poll is yes'+ str(reaction.count))
# await message.channel.send('The outcome of the poll is no')
client.run(os.getenv('TOKEN'))
我对 python 和 discord api 非常陌生,我一直在尝试建立一个轮询系统,其中每个轮询都有一个持续 24 小时的计时器,24 小时后它将对消息的反应量进行比较看哪一方获胜。有人可以帮我弄这个吗。谢谢
答案 0 :(得分:0)
我不会为此使用 on_message
事件,而是使用命令。
你可以这样做:
import discord
from discord.ext import commands
@client.command()
async def poll(ctx, *, text: str):
poll = await ctx.send(f"{text}")
await poll.add_reaction("✅")
await poll.add_reaction("❌")
这里我们将 text
作为 str
,因此您可以添加任意数量的文本。
如果您想在 24 小时后进行比较,您还必须在机器人重新启动时内置冷却保护程序,否则我们可以使用 await asyncio.sleep(TimeAmount)
如果你想用命令检查结果,我们可以这样做:
from discord.utils import get
import discord
from discord.ext import commands
@client.command()
async def results(ctx, channel: discord.TextChannel, msgID: int):
msg = await channel.fetch_message(msgID)
reaction = get(msg.reactions, emoji='✅')
count1 = reaction.count # Count the one reaction
reaction2 = get(msg.reactions, emoji="❌")
count2 = reaction2.count # Count the second reaction
await ctx.send(f"✅**: {count1 - 1}** and ❌**: {count2 - 1}**") # -1 is used to exclude the bot
命令的用法是:results #channel MSGID
。
请注意,fetch
是 API 调用,可能会导致速率限制。