Hello I have been trying to create a application bot for my server the bot sends you a questions then the person answers then its noted down ect but my problem is that sometimes the next question would send without waiting for the answer to the previous question. this only happens most of the time. try i might i have not been able to fix the problem. I’m pretty new to python and at the end of my wits.
my code for reference:
import os
from discord.ext import commands
from discord.utils import get
BOT_PREFIX = ("!")
client = commands.Bot(command_prefix=BOT_PREFIX)
a_list = []
#client.event
async def on_ready():
print ("------------------------------------")
print ("Bot Name: " + client.user.name)
print ("------------------------------------")
submit_wait = False
a_list = []
b_list = []
c_list = []
d_list = []
#client.command(aliases=['application'])
async def app(ctx):
a_list = []
b_list = []
c_list = []
d_list = []
submit_wait = False
submit_channel = client.get_channel(806404345830047744)
channel = await ctx.author.create_dm()
await channel.send("starting applaction!")
await ctx.send(ctx.author.mention + "check your dms!")
time.sleep(2)
def check(m):
return m.content is not None and m.channel == channel
await channel.send("Do you have any prior milli sim experiance?")
msg = await client.wait_for('message', check=check)
a_list.append(msg.content)
await channel.send("What time zone are you in?")
msg2 = await client.wait_for('message', check=check)
b_list.append(msg2.content)
await channel.send("If a officer ordered you to break the genva convention would you do it?")
msg3 = await client.wait_for('message', check=check)
c_list.append(msg3.content)
await channel.send("Is there any particular dvision you want to be in?")
msg4 = await client.wait_for('message', check=check)
d_list.append(msg4.content)
await channel.send('thank you for applying! a officer will do your application as soon as they can - respound with "submit" to submit your application')
msg = await client.wait_for('message', check=check)
if "submit" in msg.content.lower():
submit_wait = False
answers = "\n".join(f'{a}. {b}' for a, b in enumerate(a_list, 1))
answer = "\n".join(f'{a}. {b}' for a, b in enumerate(b_list, 2))
answerr = "\n".join(f'{a}. {b}' for a, b in enumerate(c_list, 3))
answerss = "\n".join(f'{a}. {b}' for a, b in enumerate(d_list, 4))
submit_msg = f'Application from {msg.author} \nThe answers are:\n{answers}'
submit_msg2 = f'{answer}'
submit_msg3 = f'{answerr}'
submit_msg4 = f'{answerss}'
await submit_channel.send(submit_msg)
await submit_channel.send(submit_msg2)
await submit_channel.send(submit_msg3)
await submit_channel.send(submit_msg4)
client.run(os.getenv('TOKEN'))
I tested code using print() and I think problem is because check() sometimes gets bot's question and it treats it as user's answer.
You have to check m.author in check() - something like this
#client.command(aliases=['application'])
async def app(ctx):
submit_channel = client.get_channel(806404345830047744)
#print('submit_channel:', submit_channel)
channel = await ctx.author.create_dm()
author = ctx.author
def check(m):
#print('m.author:', m.author)
#print('m.content:', m.content)
#print('m.channel:', m.channel, m.channel == channel)
return m.author == author and m.content and m.channel == channel
Minimal working code with other changes
import os
import time
from discord.ext import commands
client = commands.Bot(command_prefix="!")
#client.event
async def on_ready():
print ("------------------------------------")
print ("Bot Name:", client.user.name)
print ("------------------------------------")
#client.command(aliases=['application'])
async def app(ctx):
submit_channel = client.get_channel(806404345830047744)
print('submit_channel:', submit_channel)
channel = await ctx.author.create_dm()
author = ctx.author
def check(m):
print('m.author:', m.author)
print('m.content:', m.content)
print('m.channel:', m.channel, m.channel == channel)
return m.author == author and m.content and m.channel == channel
await channel.send("starting applaction!")
await ctx.send(ctx.author.mention + " check your dms!")
time.sleep(2)
await channel.send("Do you have any prior milli sim experiance?")
answer_a = await client.wait_for('message', check=check)
answer_a = answer_a.content
await channel.send("What time zone are you in?")
answer_b = await client.wait_for('message', check=check)
answer_b = answer_b.content
await channel.send("If a officer ordered you to break the genva convention would you do it?")
answer_c = await client.wait_for('message', check=check)
answer_c = answer_c.content
await channel.send("Is there any particular dvision you want to be in?")
answer_d = await client.wait_for('message', check=check)
answer_d = answer_d.content
await channel.send('thank you for applying! a officer will do your application as soon as they can - respound with "submit" to submit your application')
msg = await client.wait_for('message', check=check)
if "submit" in msg.content.lower():
submit_msg = f'''Application from {msg.author}
The answers are:
1. {answer_a}
2. {answer_b}
3. {answer_c}
4. {answer_d}'''
await submit_channel.send(submit_msg)
client.run(os.getenv('TOKEN'))
Ok so at first glance I'm picking up a few errors
Firstly, minor issue, but using time.sleep(2) will pause your entire bot, so if you want to let other people to run this command at the same time you may want to change this
import asyncio # instead of import time
await asyncio.sleep(2) # instead of time.sleep(2)
Also you needn't repeat so much code, this should make it work exactly how you want it to
import os
from discord.ext import commands
from discord.utils import get
import asyncio
client = commands.Bot(command_prefix="!")
#client.event
async def on_ready():
print ("------------------------------------")
print ("Bot Name: " + client.user.name)
print ("------------------------------------")
submit_wait = False
questions = ["Do you have any prior milli sim experiance?",
"What time zone are you in?",
"If a officer ordered you to break the genva convention would you do it?",
"Is there any particular dvision you want to be in?"]
#client.command(aliases=['application'])
async def app(ctx):
submit_channel = client.get_channel(810118639234973719)
channel = await ctx.author.create_dm()
await channel.send("starting applaction!")
await ctx.send(ctx.author.mention + "check your dms!")
await asyncio.sleep(2)
def check(m):
return m.content != "" and m.channel == channel
answers = []
for question in questions:
await channel.send(question)
msg = await client.wait_for("message", check=check)
answers.append(msg.content)
await channel.send('thank you for applying! a officer will do your application as soon as they can - respound with "submit" to submit your application')
msg = await client.wait_for("message", check=check)
if "submit" in msg.content.lower():
submit_wait = False
answers = [f"{no+1}. {ans}" for no, ans in enumerate(answers)]
submit_msg = [f"Application from {msg.author}",
"The answers are:", *answers]
await submit_channel.send("\n".join(submit_msg))
client.run(os.getenv('TOKEN'))
Related
this is the code. if you want any other info i can provide you with it, but as for right now this is the only place that i had hopes on. im literally stuck.
import os, json
from dotenv import load_dotenv, find_dotenv
import discord
from discord.ext import commands, tasks
import logging
import binance
from discord import Member
from discord.ext.commands import has_permissions, MissingPermissions
from binance import Client, ThreadedWebsocketManager, ThreadedDepthCacheManager
logger = logging.getLogger('discord')
logger.setLevel(logging.DEBUG)
handler = logging.FileHandler(filename = 'discord.log', encoding='utf-8', mode='w')
handler.setFormatter(logging.Formatter('%(asctime)s:%(name)s:&(message)s'))
logger.addHandler(handler)
load_dotenv(find_dotenv())
token = os.getenv("DISCORD_TOKEN")
channel_id = os.getenv('CHANNEL_ID')
binance_api_key = os.getenv('BINANCE_API_KEY')
binance_api_secret = os.getenv('BINANCE_API_SECRET')
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents, command_prefix='..')
binanceClient = Client(binance_api_key, binance_api_secret)
FAV_LIST = {}
with open('FAV_LIST.json') as f:
FAV_LIST = json.load(f)
def get_future_position(symbol):
position = None
positions = list(filter(lambda f:(f['symbol']==symbol), binanceClient.futures_account()['positions']))
if positions:
position = positions[0]
return position
#client.event
async def on_ready():
print(f'We have logged in as {client.user}')
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('hello'):
await message.channel.send('Hello!')
#commands.command()
async def add_fav(ctx, account, symbol):
FUT_SYMBOLS = [sym['symbol'] for sym in binanceClient.futures_exchange_info()['symbols']]
SPOT_SYMBOLS = [sym['symbol'] for sym in binanceClient.get_all_tickers()]
if account.upper() == "FUT":
if symbol in FUT_SYMBOLS:
FAV_LIST['FUTURES'][symbol] = {}
else:
await ctx.send("Provided SYMBOL or CRYPTO is not available in Futures")
elif account.upper() == "SPOT":
if symbol in SPOT_SYMBOLS:
FAV_LIST['SPOT'][symbol] = {}
else:
await ctx.send("Provided SYMBOL or CRYPTO is not available in SPOT")
else:
await ctx.send('Provided Account Type is not valid. Please use FUT for Futures and SPOT for spot')
with open('FAV_LIST.json','w') as f:
json.dump(FAV_LIST, f)
#commands.command()
async def favs(ctx):
message = "FUTURES FAVOURITE LIST\n"
for i, symbol in enumerate(FAV_LIST['FUTURES'].keys()):
message += str(i+1) + ". " + symbol + "--> Last Price: "+ binanceClient.get_ticker(symbol=symbol)['lastPrice']+"\n"
message += "\n\nSPOT FAVOURITE LIST"
for i, symbol in enumerate(FAV_LIST['SPOT'].keys()):
message += str(i+1) + ". " + symbol + "--> Last Price: "+ binanceClient.get_ticker(symbol=symbol)['lastPrice']+ "\n"
await ctx.send(message)
#commands.command()
async def fubln(ctx):
balance_list = binanceClient.futures_account_balance()
message = "-"*35 + "\n"
message += "-"*3 + "ACCOUNT BALANCE" + "-"*3 + "\n"
message += "-"*35 +"\n"
for balance in balance_list:
message += balance['asset']+" : "+balance['balance']+"\n"
message += "-"*35
await ctx.send(message)
#tasks.loop(seconds=60)
async def futures_position_alerts():
futures_info = binanceClient.futures_account()
positions_info = binanceClient.futures_position_information()
positions = futures_info['positions']
message_channel = await client.fetch_channel(channel_id)
print(f"Got channel {message_channel} for {channel_id}")
if float(futures_info['totalMaintMargin'])/float(futures_info['totalMarginBalance']) > 40.0:
await message_channel.send("Your positions' Margin Ratio is greater than 40%. Please consider taking a look at it.")
for position in positions:
symbol = position['symbol']
alert = False
message = "------"+symbol+" POSITION ALERT!------\n"
position_info = list(filter(lambda f:(f['symbol']==symbol),positions_info))[0]
if float(position_info['positionAmt']) != 0.0:
if float(position['unrealizedProfit']) < -1.0 :
message += "Unrealized Profit is going down! LOSS : "+ str(position['unrealizedProfit']) +"\n"
alert = True
if (float(position_info['markPrice'])-float(position_info['liquidationPrice']))/(float(position_info['entryPrice'])-float(position_info['liquidationPrice'])) <= 0.4:
message += "Mark price is moving closer to Liquidation Price. Your position may be liquidated soon.\n Mark Price:"+ str(position_info['markPrice']) +"\n Liquidation Price:"+str(position_info['liquidationPrice'])+"\n"
alert = True
if alert:
await message_channel.send(message)
#futures_position_alerts.before_loop
async def before():
await client.wait_until_ready()
print("Finished waiting")
futures_position_alerts.start()
##tasks.loop(seconds=60)
#async def favs_info():
# message = "INFO of Favourite Crytos\n\n"
# message += "FUTURES\n"
# for i, symbol in enumerate(FAV_LIST['FUTURES'].keys()):
# position = get_future_position(symbol)
# message += str(i)+". "+position['symbol']+" --> unrealizedProfit : "+position['unrealizedProfit']
# message_channel = await client.fetch_channel(channel_id)
# print(f"Got channel {message_channel} for {channel_id}")
# await message_channel.send(message)
##favs_info.before_loop
#async def before():
# await client.wait_until_ready()
# print("Finished waiting")
#favs_info.start()
# MODERATION COMMANDS #
#commands.command()
#has_permissions(kick_members=True, administrator=True)
async def kick(ctx, member:discord.Member,*,reason=None):
guild = ctx.guild
memberKick = discord.Embed(title='Kicked', description = f'You have been kicked from {guild.name} for {reason}')
await member.kick(reason=reason)
await ctx.send(f'User {member} has been kicked.')
#commands.command()
#has_permissions(ban_members=True, administrator=True)
async def ban(ctx, member:discord.Member,*,reason=None,):
guild = ctx.guild
memberBan = discord.Embed(title = 'Banned', description=f'You were banned from {guild.name} for {reason}')
await member.ban(reason=reason)
await ctx.send(f'User {member} has been banned.')
await member.send(embed=memberBan)
#commands.command()
#has_permissions(ban_members=True, administrator=True)
async def unban(self, ctx, *, member:discord.Member):
banned_users = await ctx.guild.bans()
member_name, member_discriminator = member.split('#')
for ban_entry in banned_users:
user = ban_entry.user
if (user.name, user.discriminator) == (member_name, member_discriminator):
await ctx.guild.unban(user)
await ctx.send(f'{user.name}#{user.discriminator} has been unbanned.')
return
#commands.command(pass_context=True)
#has_permissions(manage_messages=True)
async def mute(ctx,member:discord.Member, reason = None):
guild = ctx.guild
mutedRole = discord.utils.get(guild.roles, name='Muted')
memberMute = discord.Embed(title = 'Muted', description=f'You have been muted from {guild.name} for {reason}')
if mutedRole not in guild.roles:
perms = discord.Permissions(send_messages=False, speak=False)
await guild.create_role(name='Muted', permissions=perms)
await member.add_roles(mutedRole)
await ctx.send('Succesfuly created the [Muted] role and properly assigned it to the user.')
await ctx.add_role(member, mutedRole)
embed=discord.Embed(title='User muted!', description=f'**{0}** was muted by **{1}**!'.format(member, ctx.message.author, color=0xff00f6))
#commands.command(pass_context=True)
#has_permissions(manage_messages=True)
async def unmute(ctx, member:discord.Member, *, reason=None):
guild = ctx.guild
mutedRole = discord.utils.get(guild.roles, name = 'Muted')
memberUnmute = discord.Embed(title = 'Unmuted', description = f'You were unmuted from {guild.name} for {reason}')
await member.remove_roles(mutedRole)
await ctx.send(f'Unmuted {member.mention} for {reason}')
await member.send(embed=memberUnmute)
client.run(token)
#TRACEBACK#
Traceback (most recent call last):
File "c:\Users\arlit\Desktop\iceC-main\main.py", line 122, in <module>
futures_position_alerts.start()
File "C:\Users\arlit\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\tasks\__init__.py", line 398, in start
self._task = asyncio.create_task(self._loop(*args, **kwargs))
File "C:\Users\arlit\AppData\Local\Programs\Python\Python310\lib\asyncio\tasks.py", line 336, in create_task
loop = events.get_running_loop()
RuntimeError: no running event loop
sys:1: RuntimeWarning: coroutine 'Loop._loop' was never awaited
well i tried closing the loop but i didnt get it to work exactly how i wanted it to.
Edit: this is the whole code and the traceback below it. since it was too short. now ill have to add some random text since stack doesnt let me post too much code without adding some words.
You're calling futures_position_alerts.start() at the top level of your file. As the error message is telling you, you have to call it in an async context. There's an official example that you could look at.
im trying to code a discord.py bot where you can create embeds through a command, something like the embed creation function in mimu bot. i tried to code it but it dont work, any ways to make it work?
async def embed_create(ctx):
def check(message):
return message.author == ctx.author and message.channel == ctx.channel
await ctx.send('Enter your title.\nPut `none` if you do not want anything in this section.')
await client.wait_for("message", timeout = 300.0, check=check)
if message.content == "none":
title = ""
else:
title = ("message")
await ctx.send('Enter your title.\nPut `none` if you do not want anything in this section.')
await client.wait_for("message", timeout = 300.0, check=check)
if message.content == "none":
desc = ""
else:
desc = ("message")
embed = discord.Embed(title=title.content, description=desc.content, color=0xa9e9e9```
I figured out the problem and fixed it, here:
async def embed_create(ctx):
def check(message):
return message.author == ctx.author and message.channel == ctx.channel
await ctx.send('Enter your title.\nPut `none` if you do not want anything in this section.')
title = await client.wait_for("message", timeout = 300.0, check=check)
title = title.content
if title == "none":
title = "** **" # it will still be empty but not give an empty error message
else:
title = title
await ctx.send('Enter your title.\nPut `none` if you do not want anything in this section.')
desc = await client.wait_for("message", timeout = 300.0, check=check)
desc = desc.content
if desc == "none":
desc = "** **"
else:
desc = desc
embed = discord.Embed(title=title, description=desc, color=0xa9e9e9)
await ctx.send(embed=embed)
I want that when someone reacts to one emoji the bot writes as a log on chat like this:
#Santa has press 4️⃣
I tried to make it but I'm stuck.
import discord
import time
import random
from discord.ext import commands
client = discord.Client()
bot = client.user
if message.content.startswith('ººrandgame'):
original = await message.channel.send('Discover the number I my mind...')
uno = await original.add_reaction('1️⃣')
dos = await original.add_reaction('2️⃣')
tres = await original.add_reaction('3️⃣')
cuatro = await original.add_reaction('4️⃣')
cinco = await original.add_reaction('5️⃣')
seis = await original.add_reaction('6️⃣')
siete = await original.add_reaction('7️⃣')
ocho = await original.add_reaction('8️⃣')
nueve = await original.add_reaction('9️⃣')
diez = await original.add_reaction('🔟')
numbers = ['1️⃣','2️⃣','3️⃣','4️⃣','5️⃣','6️⃣','7️⃣','8️⃣','9️⃣','🔟']
#this part fails::
if(reaction.emoji == "1️⃣"):
await message.channel.send(author + "has press 1️⃣")
#the same idea with the other numbers
time.sleep(15)
finalnum = random.choice(numbers)
await message.channel.send('My number is: ' + finalnum)
print(finalnum)
client.run('blabla')
You can use a reaction_wait_for, this will always wait for the author of the message input of the specified reaction.
Below I've made a simple user reaction command but I'll leave it up to you how you would further like to improve it.
message = await ctx.send("React to a number")
one = '1️⃣'
two = '2️⃣'
await message.add_reaction(one)
await message.add_reaction(two)
def check(reaction, user):
return user == ctx.author and str(reaction.emoji) in [one, two]
member = ctx.author
while True:
try:
reaction, user = await client.wait_for("reaction_add", timeout=600.0, check=check)
if str(reaction.emoji) == one:
await ctx.send("You choose 1")
if str(reaction.emoji) == two:
await ctx.send("You choose 2")
In your code, I would also reccomend using asyncio.sleep(15) instead of time.sleep, as this causes the whole bot to stop, meaning no one can use it at all.
Make sure to import asyncio
You can also set it as a command, instead of using if message.content.startswith('ººrandgame'): , You can use
#client.command()
async def ººrandgame(ctx):
.... Rest of your code ...
Ibidem, I think that something is missing
import discord
import os
import random
import asyncio
from discord.ext import commands
client = discord.Client()
horaact = time.strftime('%H:%M:%S')
os.system('cls')
os.system('color 1f')
#client.event
async def on_ready():
print("Encendido")
print("logged in as {0.user}".format(client))
#client.command()
async def ººrandgame(ctx):
message = await ctx.send("React to a number")
one = '1️⃣'
two = '2️⃣'
await message.add_reaction(one)
await message.add_reaction(two)
def check(reaction, user):
return user == ctx.author and str(reaction.emoji) in [one, two]
member = ctx.author
while True:
try:
reaction, user = await client.wait_for("reaction_add", timeout=600.0, check=check)
if str(reaction.emoji) == one:
await ctx.send("You choose 1")
if str(reaction.emoji) == two:
await ctx.send("You choose 2")
client.run('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')
Remember, this is not the original code, it's just a test for trying your funtion
I have a python discord bot and I need it to get user input after a command, how can I do this? I am new to python and making discord bots. Here is my code:
import discord, datetime, time
from discord.ext import commands
from datetime import date, datetime
prefix = "!!"
client = commands.Bot(command_prefix=prefix, case_insensitive=True)
times_used = 0
#client.event
async def on_ready():
print(f"I am ready to go - {client.user.name}")
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=f"{client.command_prefix}python_help. This bot is made by drakeerv."))
#client.command(name="ping")
async def _ping(ctx):
global times_used
await ctx.send(f"Ping: {client.latency}")
times_used = times_used + 1
#client.command(name="time")
async def _time(ctx):
global times_used
from datetime import date, datetime
now = datetime.now()
if (now.strftime("%H") <= "12"):
am_pm = "AM"
else:
am_pm = "PM"
datetime = now.strftime("%m/%d/%Y, %I:%M")
await ctx.send("Current Time:" + ' ' + datetime + ' ' + am_pm)
times_used = times_used + 1
#client.command(name="times_used")
async def _used(ctx):
global times_used
await ctx.send(f"Times used since last reboot:" + ' ' + str(times_used))
times_used = times_used + 1
#client.command(name="command") #THIS LINE
async def _command(ctx):
global times_used
await ctx.send(f"y or n")
times_used = times_used + 1
#client.command(name="python_help")
async def _python_help(ctx):
global times_used
msg = '\r\n'.join(["!!help: returns all of the commands and what they do.",
"!!time: returns the current time.",
"!!ping: returns the ping to the server."])
await ctx.send(msg)
times_used = times_used + 1
client.run("token")
I am using python version 3.8.3. I have already looked at other posts but they did not answer my question or gave me errors. Any help would be greatly appreciated!
You'll be wanting to use Client.wait_for():
#client.command(name="command")
async def _command(ctx):
global times_used
await ctx.send(f"y or n")
# This will make sure that the response will only be registered if the following
# conditions are met:
def check(msg):
return msg.author == ctx.author and msg.channel == ctx.channel and \
msg.content.lower() in ["y", "n"]
msg = await client.wait_for("message", check=check)
if msg.content.lower() == "y":
await ctx.send("You said yes!")
else:
await ctx.send("You said no!")
times_used = times_used + 1
And with a timeout:
import asyncio # To get the exception
#client.command(...)
async def _command(ctx):
# code
try:
msg = await client.wait_for("message", check=check, timeout=30) # 30 seconds to reply
except asyncio.TimeoutError:
await ctx.send("Sorry, you didn't reply in time!")
References:
Client.wait_for() - More examples in here
Message.author
Message.channel
Message.content
asyncio.TimeoutError
With this you can make something like this
#client.command()
async def command(ctx):
computer = random.randint(1, 10)
await ctx.send('Guess my number')
def check(msg):
return msg.author == ctx.author and msg.channel == ctx.channel and int(msg.content) in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
msg = await client.wait_for("message", check=check)
if int(msg.content) == computer:
await ctx.send("Correct")
else:
await ctx.send(f"Nope it was {computer}")
I've had a few days on trying to figure that out, and the only thing that was simple for me was storing the message.content into a list and using it later.
some_list = []
user_message = message.content.split()
some_list.append(user_message)
and since I am using commands I wanted to remove that '!' and get the raw message
for i in some_list:
del i[0]# delete's command tag
I have a background loop that will spit out an emoji every X amount of minutes with a reaction attached to it. I want for when someone presses on the reaction of the message, it will delete the message and then send another message saying "messageauthor has grabbed the loot" and then add the amount to the cash json file.
Right now, my code is making the background loop work, but I am not sure how to grab the message.author.id in regards to the background loop so I can reference it in on_reaction_add. The current code is making the bot react once when it spits out the background loop and then again in on_reaction_add. I'm trying to make it wait for a user to react to the background loop message with the same emoji and not the bot.
client = discord.Client()
emoji_msg_grab = {}
try:
with open("cash.json") as fp:
cash = json.load(fp)
except Exception:
cash = {}
def save_cash():
with open("cash.json", "w+") as fp:
json.dump(cash, fp, sort_keys=True, indent=4)
def add_dollars(user: discord.User, dollars: int):
id = user.id
if id not in cash:
cash[id] = {}
cash[id]["dollars"] = cash[id].get("dollars", 0) + dollars
print("{} now has {} dollars".format(user.name, cash[id]["dollars"]))
save_cash()
async def background_loop():
await client.wait_until_ready()
while not client.is_closed:
channel = client.get_channel("479919577279758340")
emojigrab = '💰'
emojimsgid = await client.send_message(channel, emojigrab)
await client.add_reaction(emojimsgid, "💵")
user_id = emojimsgid.author.id
emoji_msg_grab[user_id] = {"emoji_msg_id": emojimsgid.id, "emoji_user_id": user_id}
await asyncio.sleep(600)
#client.event
async def on_reaction_add(reaction, user):
msgid = reaction.message.id
chat = reaction.message.channel
if reaction.emoji == "💵" and msgid == emoji_msg_grab[user.id]["emoji_msg_id"] and user.id == emoji_msg_grab[user.id]["emoji_user_id"]:
emoji_msg_grab[user.id]["emoji_msg_id"] = None
await client.send_message(chat, "{} has grabbed the loot!".format(user.mention))
await client.delete_message(reaction.message)
add_dollars(user, 250)
client.loop.create_task(background_loop())
I would use Client.wait_for_reaction instead of on_reaction_add:
async def background_loop():
await client.wait_until_ready()
channel = client.get_channel("479919577279758340")
while not client.is_closed:
emojigrab = '💰'
emojimsg = await client.send_message(channel, emojigrab)
await client.add_reaction(emojimsg, "💵")
res = await client.wait_for_reaction(emoji="💵", message=emojimsg, timeout=600,
check=lambda reaction, user: user != client.user)
if res: # not None
await client.delete_message(emojimsg)
await client.send_message(channel, "{} has grabbed the loot!".format(res.user.mention))
await asyncio.sleep(1)
add_dollars(res.user, 250)