Find Guild ID in on_ready() - Discord.py - python

I'm trying to make a random fact send at certain times. It worked before I implemented a dict to hold the random facts and it should work now, the only problem I'm running into is I can't access the guild id inside the on_ready() event. Here is what I have:
async def func(self):
await bot.wait_until_ready()
with open('guild_settings.json', 'r') as file:
guild_settings = json.loads(file.read())
------> guild_id = NEED
channel = bot.get_channel(guild_settings[guild_id]["random_facts_channel_id"])
random_messages = guild_settings[guild_id]["random_facts"].value()
if random_messages is None:
await channel.send(f"You need to add a fact first.")
else:
random_messages = random.choice(random_messages)
await channel.send(random_messages)
#commands.Cog.listener()
async def on_ready(self):
print("Bot is ready.")
with open('guild_settings.json', 'r') as file:
guild_settings = json.loads(file.read())
# Initializing scheduler
scheduler = AsyncIOScheduler()
hour = 12
minute = 0
for guild in bot.guilds:
guild_id = str(guild.id)
try:
hour = guild_settings[str(guild_id)]["random_facts_send_time"]["hour"]
minute = guild_settings[str(guild_id)]["random_facts_send_time"]["minute"]
except KeyError:
print(f"{guild_id} has a KeyError with the random fact feature.")
continue
# Sends "Your Message" at 12PM and 18PM (Local Time)
scheduler.add_job(self.func, CronTrigger(hour=hour, minute=minute, second="0"))
# Starting the scheduler
scheduler.start()
If I were able to somehow get the guild id then I'm sure it would work correctly, I just can't figure out how.
EDIT: This is what I have working so far
async def func(self):
await bot.wait_until_ready()
with open('guild_settings.json', 'r') as file:
guild_settings = json.loads(file.read())
for guild_id in guild_settings:
channel = bot.get_channel(guild_settings[guild_id]["random_facts_channel_id"])
if guild_settings[guild_id]["random_facts"] is not None:
random_facts = []
for values in guild_settings[guild_id]["random_facts"].values():
random_fact = values.split("\n")
random_facts += random_fact
try:
random_choice = random.choice(random_facts)
except IndexError:
continue
await channel.send(random_choice)
#commands.Cog.listener()
async def on_ready(self):
print("Bot is ready.")
with open('guild_settings.json', 'r') as file:
guild_settings = json.loads(file.read())
# Initializing scheduler
scheduler = AsyncIOScheduler()
hour = 12
minute = 0
for guild in bot.guilds:
guild_id = str(guild.id)
try:
hour = guild_settings[str(guild_id)]["random_facts_send_time"]["hour"]
minute = guild_settings[str(guild_id)]["random_facts_send_time"]["minute"]
except KeyError:
print(f"{guild_id} has a KeyError with the random fact feature.")
continue
# Sends "Your Message" at 12PM and 18PM (Local Time)
scheduler.add_job(self.func, CronTrigger(hour=hour, minute=minute, second="0"))
# Starting the scheduler
scheduler.start()

If your bot is on only one server, you can simply get the guild object by using discord.utils.get.
async def func(self):
await bot.wait_until_ready()
with open('guild_settings.json', 'r') as file:
guild_settings = json.loads(file.read())
guild = discord.utils.get(bot.guilds, name="guild's name")
channel = bot.get_channel(guild_settings[guild.id]["random_facts_channel_id"])
random_messages = guild_settings[guild.id]["random_facts"].value()
if random_messages is None:
await channel.send(f"You need to add a fact first.")
else:
random_messages = random.choice(random_messages)
await channel.send(random_messages)
If it's on multiple servers, you have to loop through the guilds and send the messages one by one.
async def func(self):
await bot.wait_until_ready()
with open('guild_settings.json', 'r') as file:
guild_settings = json.loads(file.read())
for guild in bot.guilds:
channel = bot.get_channel(guild_settings[guild.id]["random_facts_channel_id"])
random_messages = guild_settings[guild.id]["random_facts"].value()
if random_messages is None:
await channel.send(f"You need to add a fact first.")
else:
random_messages = random.choice(random_messages)
await channel.send(random_messages)

As #ŁukaszKwieciński said, you can just do this:
async def func():
for guild in client.guilds:
print(guild.id) #Do something with each ID
Or you can waste time and memory doing this (which was my initial approach 😔):
guildIDs = set()
#client.event
async def on_ready():
for guild in client.guilds:
guildIDs.add(guild.id)
#client.event
async def on_guild_join(guild):
guildIDs.add(guild.id)
#client.event
async def on_guild_remove(guild):
guildIDs.remove(guild.id)
guildIDs is an integer set that will contain all the IDs of all the guilds that the bot is present in. The reason I used a set is to prevent repetition of IDs.
You can then use each ID in a function like this:
async def func():
for guildID in guildIDs:
print(guildID) #Do something with each ID

I recommend using tasks extension of discord.py
If you'd like to get the code, here it is.
#tasks.loop(hours=10)
async def func():
await bot.wait_until_ready()
with open('guild_settings.json', 'r') as file:
guild_settings = json.loads(file.read())
for guild_id in guild_settings:
channel = bot.get_channel(guild_settings[guild_id]["random_facts_channel_id"])
if guild_settings[guild_id]["random_facts"] is not None:
random_facts = []
for values in guild_settings[guild_id]["random_facts"].values():
random_fact = values.split("\n")
random_facts += random_fact
try:
random_choice = random.choice(random_facts)
except IndexError:
continue
await channel.send(random_choice)
#tasks.loop(minutes=15)
async def update_interval():
hour = 12
minute = 0
for guild in bot.guilds:
guild_id = str(guild.id)
try:
hour = guild_settings[str(guild_id)]["random_facts_send_time"]["hour"]
minute = guild_settings[str(guild_id)]["random_facts_send_time"]["minute"]
except KeyError:
print(f"{guild_id} has a KeyError with the random fact feature.")
continue
func.cancel()
func.change_interval(hours=hour, minutes=minute)
I hope this is helpful.

Related

im having problems solving this error (RuntimeWarning: coroutine 'Loop._loop' was never awaited)

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.

How to send a message every x minutes?

fotddict = {}
#client.event
async def on_ready():
global fotddict
with open("factoftheday.json", "r") as f:
fotddict = json.load(f)
#client.command()
#commands.has_permissions(administrator=True)
async def fotd(ctx, channel : discord.TextChannel=None):
if channel is None:
embe=discord.Embed(title="<:redcross:781952086454960138>Error", description="**Please pass in all required arguments!**\nNeed help?** https://dsc.gg/otaysupport**", color=0x7289da)
await ctx.send(embed=embe)
else:
#are you sure embed
msg = await ctx.send(embed=embed)
def checkifnotbotfact(reaction, user):
return user != client.user
await msg.add_reaction('💡')
reaction, user = await client.wait_for("reaction_add", timeout=60.0, check=checkifnotbotfact)
if str(reaction.emoji) == "💡":
#confirm embed
global fotddict
fotddict[str(ctx.guild.id)] = channel.id
with open("factoftheday.json", "w") as f:
json.dump(fotddict, f)
#tasks.loop(seconds=10)
async def factsend(member):
x = randfacts.getFact()
channel_id = fotddict[str(member.guild.id)]
embed = discord.Embed(title="💡Fact of the day!", description=x, color=0x7289da)
await client.get_channel(channel_id).send(embed=embed)
#factsend.before_loop
async def before():
factsend.start()
await client.wait_until_ready()
Problem: This is my fact of the day command, it adds the channel id + guild id in a json file (so that isnt the problem). I think the problem is the loop, since that is the part that im not sure of if thats correct.
Goal: Bot sends a message with a fact every 24 hours (Task is set to 10 seconds for test purposes)
Firstly your #factsend.before_loop function is called just before the loop execution, so you have to start the loop in other place, not in the function. So you have to deplace factsend.start() outside of this function.
The corriged code will be:
#client.event
async def on_ready():
global fotddict
with open("factoftheday.json", "r") as f:
fotddict = json.load(f)
#client.command()
#commands.has_permissions(administrator=True)
async def fotd(ctx, channel : discord.TextChannel=None):
if channel is None:
embe=discord.Embed(title="<:redcross:781952086454960138>Error", description="**Please pass in all required arguments!**\nNeed help?** https://dsc.gg/otaysupport**", color=0x7289da)
await ctx.send(embed=embe)
else:
#are you sure embed
msg = await ctx.send(embed=embed)
def checkifnotbotfact(reaction, user):
return user != client.user
await msg.add_reaction('💡')
reaction, user = await client.wait_for("reaction_add", timeout=60.0, check=checkifnotbotfact)
if str(reaction.emoji) == "💡":
#confirm embed
global fotddict
fotddict[str(ctx.guild.id)] = channel.id
with open("factoftheday.json", "w") as f:
json.dump(fotddict, f)
#tasks.loop(seconds=10)
async def factsend(member):
x = randfacts.getFact()
channel_id = fotddict[str(member.guild.id)]
embed = discord.Embed(title="💡Fact of the day!", description=x, color=0x7289da)
await client.get_channel(channel_id).send(embed=embed)
#factsend.before_loop
async def before():
await client.wait_until_ready()
factsend.start() #deplaced outside of the function
Have a nice day!
If you are going to leave the bot running locally (or host it somewhere), then you should use Advance Python Scheduler
from apscheduler.schedulers.blocking import BlockingScheduler
#Code goes Here
scheduler = BlockingScheduler()
scheduler.add_job(function_name_you_want_to_run(), 'interval', hours=24)
scheduler.start()

Discord Py Tasks. Won't Run task

I need help with the following code:
import discord
from discord.ext import commands, tasks
import os
TOKEN = "tokenthing"
client = commands.Bot(command_prefix="$$")
#client.event
async def on_ready():
test.start()
print("Succesful Login as {0.user}".format(client))
#client.command()
async def GiveMoney(ctx, user : discord.User, value : int):
if value <= 0:
await ctx.send("Can't send negative money.")
return
else:
pass
sender = str(ctx.author)
reciever = str(user)
if os.path.exists(sender+".txt"):
pass
else:
await ctx.send("You Don't have an account. Type $$CreateAccount to create one.")
return
if os.path.exists(reciever+".txt"):
pass
else:
await ctx.send("The Person you are trying to give money doesn't have a bank Account")
return
try:
f= open(sender+".txt", "r")
balance = f.read()
f.close()
balance = int(balance)
balance = balance - value
balance = str(balance)
f = open(sender+".txt", "w")
f.write(balance)
f.close()
except FileNotFoundError:
await ctx.send("You don't have a Bank account. Type $$CreateAccount to create one.")
return
try:
f = open(reciever+".txt", "r")
balance = f.read()
f.close()
balance = int(balance)
balance = balance + value
balance = str(balance)
f = open(reciever+".txt", "w")
f.write(balance)
f.close()
except FileNotFoundError:
await ctx.send("The Person You are sending money dosen't have an account")
print("{0} sent {1} to {2}".format(sender, value, reciever))
#tasks.loop(seconds=10)
async def test(ctx):
for i in range(10):
print(i)
client.run(TOKEN)
I can't seem for the life of me to get it to run the task on bot readiness.
I'm not getting any error or anything it just seems to skip it.
I am using Discord.py-rewrite on a windows 10 machine.
I suspect I missed something with the commands but I'm not sure.
Thanks
Just add await when you start your loop. Because your function is async. Example:
#client.event
async def on_ready():
await test.start()

Counting invites for new members

I'm trying to get the possible invite for users that join on discord But it simply doesn't work and I don't know why. I'd expect it to output "couldn't find invite" for bots but instead it says nothing at all, not for users, nor bots. It should work to my knowledge. It scans every invite in the servers and stores them, then it checks if it goes up on the user that joins and outputs the embed.
def __init__(self, bot):
self.bot.loop.create_task(self.get_invites())
async def get_invites(self):
for guild in self.bot.guilds:
try:
guild_invites = {}
invites = await guild.invites()
for invite in invites:
guild_invites[invite.code] = invite
self.invites[guild] = guild_invites
except discord.errors.Forbidden:
pass
async def find_possible_invites(self,guild):
i = 1
while i < 11:
new = await guild.invites()
res = []
for invite in new:
try:
old_uses = self.invites[guild][invite.code].uses
except KeyError:
self.invites[guild][invite.code] = invite
if invite.uses >= 1:
res.append(invite)
continue
new_uses = invite.uses
if old_uses < new_uses :
self.invites[guild][invite.code] = invite
res.append(invite)
if res == []:
await asyncio.sleep(3)
i+=1
else:
break
return res
#commands.Cog.listener()
async def on_member_join(self,member):
server = await self.bot.get_guild(SERVER_ID)
possible_invites = await self.find_possible_invites(server)
channel = self.bot.get_channel(CHANNEL_ID)
whtspace= "** **"
embed = discord.Embed(color=0x21d3f3)
embed.title = "Member Joined!"
embed.add_field(name="Name",value=str(member))
embed.add_field(name="User ID:",value=member.id)
if len(possible_invites) == 1:
embed.add_field(name="Invite used",value=possible_invites[0].url,inline=True)
embed.add_field(name="Invite created by",value=str(possible_invites[0].inviter),inline=True)
embed.add_field(name="Number of uses",value=str(possible_invites[0].uses),inline=True)
elif len(possible_invites) > 1:
embed.add_field(name="Possible invites used:",value=whtspace,inline=False)
for i in possible_invites:
embed.add_field(name=whtspace,value=i.url,inline=False)
else:
await channel.send("Invite used could not be detected")
await channel.send(embed=embed)

Background Loop with Reactions Discord.Py

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)

Categories

Resources