discord bot python invalid syntax - python

i am working on a python bot but i've come across a syntax error with ELIF and IF statements, and ive tried fiddling around changing the elif around, and adding an else instead n such, but i can't get it to work, so that's why i come on here to see if anyone has a solution for my problem, thanks.
My code:
#bot.command()
async def linkdiscord(ctx, token):
author = ctx.message.author
author2 = str(ctx.message.author)
discordid = ctx.message.author.id
response = json.loads(requests.get(forumurl + f"/api?action=linkdiscord&key=SECRET&token={token}&discordid={discordid}").text)
if response["status"] == 200:
embed=discord.Embed(title="Linker System", color=0xcd65f0)
embed.add_field(name="Linked Discord", value="Yes", inline=True)
embed.set_footer(text="Successfully linked " + author2 + " to forum account: " + response["username"])
elif response["status"] == 400:
embed=discord.Embed(title="Linker System", color=0xff0000)
embed.add_field(name="Unexpected error", value="True", inline=True)
embed.add_field(name="Message", value= response["message"], inline=True)
embed.set_footer(text="Error")
await ctx.send(embed=embed)
await ctx.message.delete()
elif response["status"] == 420:
server_id = 741131311467516961
server = client.get_guild(server_id)
member = server.get_member(ctx.message.author.id)
await ctx.guild.ban(member, reason=response["reason"])
Regards.

Python scope is determined by whitespace; The await calls should be in the elif scope.
Also, it's considered best practice to use 4 spaces for each indent. See PEP8 for more details.
#bot.command()
async def linkdiscord(ctx, token):
author = ctx.message.author
author2 = str(ctx.message.author)
discordid = ctx.message.author.id
response = json.loads(requests.get(forumurl + f"/api?action=linkdiscord&key=SECRET&token={token}&discordid={discordid}").text)
if response["status"] == 200:
embed=discord.Embed(title="Linker System", color=0xcd65f0)
embed.add_field(name="Linked Discord", value="Yes", inline=True)
embed.set_footer(text="Successfully linked " + author2 + " to forum account: " + response["username"])
elif response["status"] == 400:
embed=discord.Embed(title="Linker System", color=0xff0000)
embed.add_field(name="Unexpected error", value="True", inline=True)
embed.add_field(name="Message", value= response["message"], inline=True)
embed.set_footer(text="Error")
await ctx.send(embed=embed) # Now I'm in the correct scope!
await ctx.message.delete() # Me too!
elif response["status"] == 420:
server_id = 741131311467516961
server = client.get_guild(server_id)
member = server.get_member(ctx.message.author.id)
await ctx.guild.ban(member, reason=response["reason"])

Related

How do I make my bot's Slash response detect reactions in discord.py?

I have been using this function before Discord forced everyone to switch to slash commands. Now, when I move it to slash command format, it doesn't work.
What used to work, now doesn't. I'm using this inside a cogs file. If that helps, great. If not, sorry.
async def combat_shop(self, ctx):
member_id = ctx.author.id
await utils.refresh_active(ctx, member_id, ctx.author.name)
bancheck = await utils.ban_check(ctx)
if bancheck is True:
await ctx.send("<:BanHammer_:957349442573467708>┃You've been banned from using Daddy Bot. Take this to the support server: <https://discord.gg/SbMyaxWFr9> \nRemember: Being rude/commanding ***will not*** do you any good. Be kind and respectful.")
return
await utils.leveling_system(ctx, 5)
dec = "buy: `daddy buy >id<`\ndismantle: `daddy dismantle >id<`\n\n`r-combat`┃Random Combat Item┃<:Dollar:952432145270452244> 250k"
page1CS = embed = discord.Embed(title = "**The Weapon Store<:D_Axe:998668619561046077>**", description = f"{dec}", color = discord.Colour.teal())
embed.add_field(name="Basic Weapons", value="`long_sword`┃<:D_LongSword:1001951918706397235> **Long Sword**┃<:D_WeaponParts:998668591174000690> 10\n`short_sword`┃<:D_ShortSword:998668579207663616>**Short Sword**┃<:D_WeaponParts:998668591174000690> 20\n`halberd`┃<:D_Halberd:1001951880215277738>**Halberd**┃<:D_WeaponParts:998668591174000690>50\n`axe`┃<:D_Axe:998668619561046077>**Axe**┃<:D_WeaponParts:998668591174000690> 35\n`gun`┃<:D_Gun:1002626237618995351>**Gun**┃<:D_WeaponParts:998668591174000690> 20\n`star_blaster`┃<:D_StarBlaster:1001951963828715641>**Star Blaster**┃<:D_WeaponParts:998668591174000690> 150", inline=True)
embed.add_field(name="Patreon Weapons", value="`lightning_spear`┃<:D_LightningSpear:998668565408403526>**Lightning Spear**┃<:D_WeaponParts:998668591174000690> 50\n`potato_bomb`┃<:D_PotatoBomb:998668568755445830>**Potato Bomb**┃<:D_WeaponParts:998668591174000690> 100\n`shadow_dagger`┃<:D_ShadowDagger:998668575747358810>**Shadow Dagger**┃<:D_WeaponParts:998668591174000690> 50", inline=True)
embed.set_footer(text="page 1/5")
page2CS = embed = discord.Embed(title = "**The Armor Store<:D_ShadowHelmet:998668576930152508>**", description = f"{dec}", color = discord.Colour.teal())
embed.add_field(name="Basic Armor Sets", value="`speedy_helmet`┃<:D_SpeedyHelmet:998668582777008238>**Speedy Helmet**┃<:D_ArmorParts:998668617866559519> 15\n`speedy_armor`┃<:D_SpeedyArmor:998668581917184090>**Speedy Armor**┃<:D_ArmorParts:998668617866559519> 20\n`turtle_shell_helmet`┃<:D_TurtleShellHelmet:998668588107968522>**Turtle Helmet**┃<:D_ArmorParts:998668617866559519>25\n`turtle_shell_armor`┃<:D_TurtleShellArmor:998668586749010081>**Turtle Armor**┃<:D_ArmorParts:998668617866559519> 30\n`leather_helmet`┃<:D_LeatherHelmet:998668559632842873>**Leather Helmet**┃<:D_ArmorParts:998668617866559519> 20\n`leather_armor`┃<:D_LeatherArmor:998668558299041812>**Leather Armor**┃<:D_ArmorParts:998668617866559519> 25", inline=True)
embed.add_field(name="Patreon Armor Sets", value="`shadow_helmet`┃<:D_ShadowHelmet:998668576930152508>**Shadow Helmet**┃<:D_ArmorParts:998668617866559519> 50\n`shadow_armor`┃<:D_ShadowArmor:998668574631661608>**Shadow Armor**┃<:D_ArmorParts:998668617866559519> 60\n`potato_helmet`┃<:D_PotatoHelmet:998668571683078225>**Potato Helmet**┃<:D_ArmorParts:998668617866559519> 150\n`potato_armor`┃<:D_PotatoArmor:998668567673323590>**Potato Armor**┃<:D_ArmorParts:998668617866559519> 200\n`zeus_helmet`┃<:D_ZeusHelmet:998668593363423322>**Zeus Helmet**┃<:D_ArmorParts:998668617866559519> 50\n`zeus_armor`┃<:D_ZeusArmor:998668592126115973>**Zeus Armor**┃<:D_ArmorParts:998668617866559519> 60", inline=True)
embed.set_footer(text="page 2/5")
page3CS = embed = discord.Embed(title = "**The Secondary Store<:D_HealingPotion:998668556856197291>**", description = f"{dec}", color = discord.Colour.teal())
embed.add_field(name="Basic Secondary", value="`strength_staff`┃<:D_StrengthStaff:998668583959810088>**Strength Staff**┃<:D_WeaponParts:998668591174000690> 50\n`defense_staff`┃<:D_DefenseStaff:998668620823531531>**Defense Staff**┃<:D_WeaponParts:998668591174000690> 50\n`shield`┃<:D_Shield:998668578091970580>**Shield**┃<:D_WeaponParts:998668591174000690> 50", inline=True)
embed.add_field(name="Patreon Secondary", value="`walking_cane`┃<:D_WalkingCane:998668589747945562>**Walking Cane**┃<:D_WeaponParts:998668591174000690> 75\n`potato_buddy`┃<:D_PotatoBuddy:998668569946620045>**Potato Buddy**┃<:D_WeaponParts:998668591174000690> 150\n`thunder_rod`┃<:D_ThunderRod:998668564196241418>**Thunder Rod**┃<:D_WeaponParts:998668591174000690> 75", inline=True)
embed.set_footer(text="page 3/5")
page4CS = embed = discord.Embed(title = "**The Special Store<:D_PotatoParty:998668573004284008>**", description = f"{dec}", color = discord.Colour.teal())
embed.add_field(name="Basic Specials", value="`earthquake`┃<:D_Earthquake:998668623512084560>**Earthquake**┃<:Dollar:952432145270452244> 1m\n`life_steal`┃<:D_LifeSteal:998668560706572458>**Life Steal**┃<:Dollar:952432145270452244> 1m", inline=True)
embed.add_field(name="Patreon Specials", value="`nightmare`┃<:D_Nightmare:998668566146592795>**Nightmare**┃<:Dollar:952432145270452244> 1m\n`potato_party`┃<:D_PotatoParty:998668573004284008>**Potato Party**┃<:Dollar:952432145270452244> 1m\n`thunderstorm`┃<:D_ThunderStorm:998675226743275530>**Thunderstorm**┃<:Dollar:952432145270452244> 1m\n`healing_orb`┃<:D_HealingOrb:998668625097543750>**Healing Orb**┃<:Dollar:952432145270452244> 1m", inline=True)
embed.set_footer(text="page 4/5")
page5CS = embed = discord.Embed(title = "**The Items Store<:D_HealingPotion:998668556856197291>**", description = f"{dec}", color = discord.Colour.teal())
embed.add_field(name="Items", value="`healing_potion`┃<:D_HealingPotion:998668556856197291>**Healing Potion**┃<:Dollar:952432145270452244> 50k\n`bomb`┃<:D_Bomb:1001952068837330984>**Bomb**┃<:Dollar:952432145270452244> 50k\n`damage_upgrade`┃<:D_DamageUpgradeStone:998668585251651735>**Damage Upgrade**┃<:Dollar:952432145270452244> 250k\n`defense_upgrade`┃<:D_DefenseUpgradeStone:998668621951795281>**Defense Upgrade**┃<:Dollar:952432145270452244> 250k\n`speed_upgrade`┃<:D_SpeedUpgradeStone:998668580902150144>**Speed Upgrade**┃<:Dollar:952432145270452244> 250k")
embed.set_footer(text="page 5/5")
test_pages_shop = [page1CS, page2CS, page3CS, page4CS, page5CS]
buttons_shop = ["◀", "▶"]
current_shop = 0
msg = await ctx.send(embed=test_pages_shop[current_shop])
for button in buttons_shop:
await msg.add_reaction(button)
while True:
try:
reaction, user = await self.bot.wait_for("reaction_add", check=lambda reaction, user: user == ctx.author and reaction.message == msg and reaction.emoji in buttons_shop, timeout=25)
except asyncio.TimeoutError:
await msg.clear_reactions()
break
return
else:
previous_pages = current_shop
if reaction.emoji == "◀":
if current_shop > 0:
current_shop -= 1
elif reaction.emoji == "▶":
if current_shop < len(test_pages_shop) - 1:
current_shop += 1
for button in buttons_shop:
await msg.remove_reaction(button, ctx.author)
if current_shop != previous_pages:
await msg.edit(embed=test_pages_shop[current_shop])
Keep in mind that I removed the #cog_ext.cog_slash part because that's not the issue. I've been doing testing beforehand and I found that it gets stuck on the #cog_ext.cog_slash part.
To convert this command, you'll need these changes to the function definition
#app_commands.command(name="combat_shop", description="The Combat shop")
async def combat_shop(self, interaction : discord.Interaction):
You'll also need to adapt your code to deal with a discord.Interaction instead of a discord.ext.commands.Context.
That includes switching:
ctx.send to interaction.response.send_message
Switching the msg.edit to one of the interaction edits (e.g. interaction.edit_original_response)
ctx.author to interaction.user
I found out the issue after another hour of testing. In slash commands, it has to be reaction.message.id == msg.id for that check to work.

discord.py command that create embed

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)

Bot isn't responding to my command | discord.py

So I was making a work command, and I needed some help. The bot was not responding unless I put my id into the json file instead of the bot doing it automatically. I don't get any error either. Again, it only works unless I manually put the id into the json file.
Here's the code:
youtuber = {}
def youtube():
global youtuber
try:
with open ('youtuber.json', "a") as f:
youtuber = json.load(f)
except FileNotFoundError:
print("File not found")
developer = {}
def developing():
global developer
try:
with open('developer.json', "a") as f:
developer = json.load(f)
except FileNotFoundError:
print("Error")
scientist = {}
def science():
global scientist
try:
with open('scientist.json', "a") as f:
scientist = json.load(f)
except FileNotFoundError:
print("Error")
#commands.command()
async def work(self, ctx):
await open_account(ctx.author)
#Variables
salary = 2000
id = str(ctx.author.id)
#If user is unemployed :laughard:
if id not in developer and scientist and youtuber:
await ctx.send("Your unemployed, You can work as a `developer` or a `scientist` or a `youtuber` or a `doctor`. Pick one.\n\nNote: All jobs have the same amount of salary")
message = await self.bot.wait_for('message', check = lambda: message.author == ctx.author)
#Developer
if message.content == "developer":
developer[id] = 1
with open('developer.json', 'a') as f:
json.dump(developer, f)
await ctx.send("Congratualations! You now work as a developer!")
return
#youtuber
elif message.content == "youtuber":
youtuber[id] = 1
with open('scientist.json', 'a') as f:
json.dump(scientist, f)
await ctx.send("Congratualations! You now work as a youtuber!")
return
#scientist
elif message.content == "scientist":
scientist[id] = 1
with open('youtuber.json', 'a') as f:
json.dump(youtuber, f)
await ctx.send("Congratualations! You now work as a scientist!")
return
#Dev work
elif id in developer:
dev_work = ["Type the following: `Python is the best. Everything else is trash.`", "Type the following: `Time to steal some code.`", "Answer the following question: `Which is the best bot in the world?`"]
rand_dev = random.choice(dev_work)
await ctx.send(rand_dev)
message = await self.bot.wait_for('message', check=lambda : message.author == ctx.author)
if rand_dev == dev_work[0]:
if message.content == "Python is the best. Everything else is trash.":
await ctx.send("You have earned 2000 coins!")
else:
await ctx.send("You can't even type a sentence properly? You get 0 coins")
return
elif rand_dev == dev_work[1]:
if message.content == "Time to steal some code.":
await ctx.send("You have earned 2000 coins!")
else:
await ctx.send("You can't even type a sentence properly? Dumb")
return
elif rand_dev == dev_work[2]:
if message.content == "LeBot":
await ctx.send("You have earned 2000 coins!")
else:
await ctx.send("It's LeBot......")
return
#Youtube work
elif id in youtuber:
youtuber_work = ["Type the following: `I wish I had 100mil sub's like pewdiepie.`", "Type the following: `The Hair Trilogy is the best trilogy to ever exist.`", "Type the following: `Papa Franku please come back.`"]
rand_youtube = random.choice(youtuber_work)
await ctx.send(rand_dev)
message = await self.bot.wait_for('message', check=lambda : message.author == ctx.author)
if rand_youtube == youtuber_work[0]:
if message.content == "I wish I had 100mil sub's like pewdiepie.":
await ctx.send("You have earned 2000 coins!")
else:
await ctx.send("You can't even type a sentence properly? Dumb")
return
elif rand_youtube == youtuber_work[1]:
if message.content == "The Hair Trilogy is the best trilogy to ever exist.":
await ctx.send("You have earned 2000 coins!")
else:
await ctx.send("You can't even type a sentence properly? Dumb")
return
elif rand_youtube == youtuber_work[2]:
if message.content == "Papa Franku please come back.":
await ctx.send("You have earned 2000 coins!")
else:
await ctx.send("You can't even type a sentence properly?")
return
#scientist work
elif id in scientist:
science_work = ["Type the following: `I wonder if waterproof spray can make me walk on water.`", "Type the following: `Don't trust atoms! They make everything up!`", "Type the following: `No I'm not Elon Musk, I can't make a rocket land by itself.`"]
rand_science = random.choice(science_work)
await ctx.send(rand_science)
message = await self.bot.wait_for('message', check=lambda : message.author == ctx.author)
if rand_science == science_work[0]:
if message.content == "I wonder if waterproof spray can make me walk on water.":
await ctx.send("You have earned 2000 coins!")
else:
await ctx.send("You can't even type a sentence properly? Dumb")
return
elif rand_science == science_work[1]:
if message.content == "Don't trust atoms! They make everything up!":
await ctx.send("You have earned 2000 coins!")
else:
await ctx.send("You can't even type a sentence properly? Dumb")
return
elif rand_science == science_work[2]:
if message.content == "No I'm not Elon Musk, I can't make a rocket land by itself.":
await ctx.send("You have earned 2000 coins!")
else:
await ctx.send("You can't even type a sentence properly?")
return
Any help will be appreciated!

How to loop with a reaction embed menu

What I'm trying to do: Learning to make a proper help menu for my discord.py bot by having the ctx.message.author react to the message with the reactions given. The bot checks if they've been reacted to, then edits the message. If the ctx.message.author un-reacts, it goes back to the first menu (menuu).
Problem(s): I'm not sure how to loop through this until the timeout runs out. I'm also not sure how to check if the user un-reacts to the message.
Error(s): No errors.
#client.command()
async def menuu(ctx):
#what reaction goes where menuu
menuu = discord.Embed(title="menuu", color=0x8d78d9)
menuu.add_field(name="Topics: ", value="React with <:oneone:772681764321099827>", inline=False)
menuu.add_field(name="Games: ", value="React with <:twotwo:772681764271423528>", inline=False)
menuu.add_field(name="Misc: ", value="React with <:threethree:772681763939024897>", inline=False)
menuu.set_footer(text=f"Ensure you drink some water today, you're doing so well {ctx.message.author}")
#topics menuu
topics = discord.Embed(title="Topics", color=0x8d78d9)
topics.add_field(name="`bl!topic`: ", value="Friend makers and ice breakers", inline=False)
topics.add_field(name="`bl!debate`: ", value="menuu not complete sorry haha")
topics.set_footer(text="Never forget to believe in yourself, because I do!")
#game menuu
games = discord.Embed(title="Games", color=0x8d78d9)
games.add_field(name="`nothing here`: ", value="Technically there is but still", inline=False)
games.set_footer(text="Eat some food, take a nap, good luck on the journey ahead")
#misc menuu
misc = discord.Embed(title="Misc", color=0x8d78d9)
misc.add_field(name="`miscmimscimc`: ", value="aeaeaeaeaeaeeae", inline=False)
misc.set_footer(text="You look lovely today, you're rocking this look")
msg = await ctx.send(embed=menuu)#send message
#add reactions things
await msg.add_reaction("<:oneone:772681764321099827>")
await msg.add_reaction("<:twotwo:772681764271423528>")
await msg.add_reaction("<:threethree:772681763939024897>")
await msg.add_reaction("<:stop:773054889685024768>")
try:
def check(reaction, user):
return user == ctx.message.author and str(reaction.emoji) in ["<:oneone:772681764321099827>","<:twotwo:772681764271423528>","<:threethree:772681763939024897>"]
reaction, user = await client.wait_for("reaction_add", timeout=60, check=check)
if str(reaction.emoji) == "<:oneone:772681764321099827>":
await msg.edit(embed=topics)
await msg.remove_reaction("<:oneone:772681764321099827>", ctx.message.author)
if str(reaction.emoji) == "<:twotwo:772681764271423528>":
await msg.edit(embed=games)
await msg.remove_reaction("<:twotwo:772681764271423528>", ctx.message.author)
if str(reaction.emoji) == "<:threethree:772681763939024897>":
await msg.edit(embed=misc)
await msg.remove_reaction("<:threethree:772681763939024897>", ctx.message.author)
if str(reaction.emoji) == "<:stop:773054889685024768>":
await msg.edit(embed=menuu)
await msg.remove_reaction("<:stop:773054889685024768>", ctx.message.author)
except asyncio.TimeoutError:
await ctx.send("Time has run out, message no work now")
```
I've created an easy enough to use 'book-manager'. If you put all of your menuus into a list called pages you can use this function:
async def createbook(bot, ctx, title, pages, **kwargs):
header = kwargs.get("header", "") # String
results = kwargs.get("results", 0) # Int
pagenum = 1
def get_results():
results_min = (pagenum - 1) * 8 + 1
if pagenum == len(pages): results_max = results
else: results_max = pagenum * 8
return f"Showing {results_min} - {results_max} results out of {results}"
pagemax = len(pages)
if results:
header = get_results()
if len(pages) == 0: pagemax = 1
embed = discord.Embed(title=title, description=f"{header}\n\n{pages[pagenum - 1]}", colour=0xF42F42)
embed.set_footer(text=f"Page {pagenum}/{pagemax}", icon_url=fboturl)
msg = await ctx.send(embed=embed)
await msg.add_reaction("⬅️")
await msg.add_reaction("➡")
def check(reaction, user):
return user == ctx.author and str(reaction.emoji) in ["⬅️", "➡"]
while True:
try:
reaction, user = await bot.wait_for("reaction_add", timeout = 60, check=check)
await msg.remove_reaction(reaction, user)
if str(reaction.emoji) == "⬅️":
pagenum -= 1
if pagenum < 1: pagenum = len(pages)
elif str(reaction.emoji) == "➡":
pagenum += 1
if pagenum > len(pages): pagenum = 1
header = get_results() if results else header
if str(reaction.emoji) == "⬅️" or str(reaction.emoji) == "➡":
embed = discord.Embed(title=title, description=f"{header}\n\n{pages[pagenum - 1]}", colour=0xF42F42)
embed.set_footer(text=f"Page {pagenum}/{len(pages)}", icon_url=fboturl)
await msg.edit(embed=embed)
except:
header = get_results() if results else header
embed = discord.Embed(title="FBot Server Status", description=f"{header}\n\n{pages[pagenum - 1]}", colour=0xF42F42)
embed.set_footer(text=f"Request timed out", icon_url=fboturl)
await msg.edit(embed=embed)
break
(I avoid using numbers purely because books with more than 10 pages are annoying to manage)
So after a really long time of trial and error, I have figured out my own method based off of Judev1's create-book thing. I incorporated the way the page number changes, as well as the wait_for and time out things.
#client.command(aliases=["help"])
async def menuu(ctx):
#first just giving all the embeds a purpose and a place to exist
user = ctx.author
menuu = discord.Embed(title="Help Menuu", color=0x8d78d9)
menuu.add_field(name="How to navigate : ", value="```Use the arrow reactions below to navigate this menuu```", inline=False)
menuu.add_field(name="How to invite bot : ", value="```Use bl!invite to invite this bot and join our support server!```", inline=True)
menuu.set_footer(text=f"Ensure you drink some water today, you're doing so well {ctx.message.author}")
#topics menuu
topics = discord.Embed(title="Topics", color=0x8d78d9)
topics.add_field(name="bl!topic : ", value="```Friend makers and ice breakers```", inline=False)
topics.add_field(name="bl!debate : ", value="```Sends a debate topic (Trigger Warning: Some topics may trigger certain individuals. Please tread with caution when using this command)```", inline=False)
topics.add_field(name="bl!wyr : ", value="```Would you rather questions```", inline = False)
topics.add_field(name="bl!place : ", value="```So many places in the world, so little time```", inline = True)
topics.set_footer(text="Never forget to believe in yourself, because I do!")
#game menuu
games = discord.Embed(title="Games", color=0x8d78d9)
games.add_field(name=f"bl!powpow `#blitz` : ", value="```Who will win? You, or that person you mentioned?```", inline=False)
games.add_field(name=f"bl!battle `#blitz` : ", value="```Basically powpow but less work```", inline=True)
games.set_footer(text="Eat some food, take a nap, good luck on the journey ahead")
#pics menuu
pics = discord.Embed(title="Picture Things:tm:", color=0x8d78d9)
pics.add_field(name="bl!avatar `#blitz` : ", value="```Get the profile picture of the mentioned person```", inline=False)
pics.add_field(name="bl!hug `#blitz` : ", value="```Hugs, many hug gifs :)```", inline= True)
pics.add_field(name="bl!slap `#blitz` : ", value="```Slap whoever you want without the pain```", inline=False)
pics.set_footer(text="You look lovely today, you're rocking this look")
##send message##
msg = await ctx.send(embed=menuu)
pages = 1 #page it's currently on
left = "<a:totheleft:767541559440572427>" #left arrow reaction
right = "<a:totheright:767541574287884309>" #right arrow reaction
await msg.add_reaction(left) #add reaction to send menuu
await msg.add_reaction(right) #and again
def check(reaction, user): #checking if user is author and the reaction is either left or right (as defined earlier)
return user == ctx.author and str(reaction.emoji) in [left, right]
while True:
try:
reaction, user = await client.wait_for("reaction_add", timeout = 120, check=check)
await msg.remove_reaction(reaction, user)
if str(reaction.emoji) == left:
pages = pages - 1
if pages < 1:
pages = 4 #if pages is less than 1, go straight to 4
if str(reaction.emoji) == right:
pages = pages + 1
if pages > 4:
pages = 1 #if pages is more than 4, go back to 1
#if this is the page number, edit so it's this embed instead
if pages == 1:
await msg.edit(embed=menuu)
elif pages == 2:
await msg.edit(embed=topics)
elif pages == 3:
await msg.edit(embed=games)
elif pages == 4:
await msg.edit(embed=pics)
except: #timeout error handling
embed = discord.Embed(title="Run command again to use", description="Have a good day {ctx.author.display_name}! `bl!menuu`")
await msg.edit(embed=embed)
break

How to make a function that is done every 24 hours without stopping the whole program with time.sleep() for that time?

I have a Discord bot that stores a deadline for a user in a message channel. After the deadline ends, I want the bot to notify the moderators so they can deal with it.
Everything for the bot besides that is already done. My idea for this issue is to just have a function that checks the channel with deadlines every 24 hours and finds the same date on it as the current date and takes out the userid (which is also stored in said message).
I'm open to other solutions for this problem.
I've read up and Googled a bunch. It, at least, seems like to me that time.sleep() and schedule.every will stop my whole program for that time, but maybe I'm wrong about the schedule thing, because I tried to implement it into my code, but I got no idea how to make it work. I have only a week of Python experience here, bear with me.
Here is pretty much my whole code if it helps (without the bot token part, of course)
import datetime
import discord
from discord.ext.commands import Bot
from discord.ext import commands
import asyncio
import time
import random
from discord import Game
from discord.utils import get
from datetime import datetime, timedelta
Client = discord.client
client = commands.Bot(command_prefix = '%')
Clientdiscord = discord.Client()
#client.event
async def on_ready():
await client.change_presence(game=Game(name='with nuclear waste'))
print('Ready, bitch')
#client.event
async def on_reaction_add(reaction, user):
if ' has sent an application to become a full fledged FRICK' in reaction.message.content:
Name = reaction.message.content.split('#')
usid = reaction.message.content.split('=')
usid1 = usid[1].split(' ')
user =reaction.message.server.get_member(usid1[0])
msg = reaction.message.content.split('?')
eventcode = str (msg[1])
cont = str(msg[0])
kakapoopoo = '#' + usid1[0]
#await client.send_message(user, 'test')
if reaction.emoji == get(client.get_all_emojis(), name='FeelsBadMan'):
await client.send_message(client.get_channel('560678137630031872'), Name[0] + ' has attented 1 event.')
await client.edit_message(reaction.message, cont + '?01')
if reaction.emoji == get(client.get_all_emojis(), name='veetsmug'):
await client.send_message(client.get_channel('560678137630031872'), Name[0] + ' has attented 2 events.')
await client.edit_message(reaction.message, cont + '?10')
if reaction.emoji == get(client.get_all_emojis(), name='POGGERS'):
await client.edit_message(reaction.message, cont + '?11')
await client.send_message(client.get_channel('560678137630031872'), Name[0] + ' has attented 3 events.')
if reaction.emoji == get(client.get_all_emojis(), name='HYPERS'):
role1 = discord.utils.get(reaction.message.server.roles, name='Pending Frick')
await client.remove_roles(user, role1)
await client.send_message(client.get_channel('560678137630031872'), user.mention + ' has attented 4 events and is now a ***FRICK***.\n#here')
role2 = discord.utils.get(reaction.message.server.roles, id='561087733834186754')
await client.add_roles(user, role2)
await client.send_message(user, 'You are now a full fledged ***FRICK***')
await client.delete_message(reaction.message)
elif 'To approve screenshot react with :HYPERS: to dissaprove react with :FeelsBadMan:' in reaction.message.content:
cunt = reaction.message.content.split('#')
name = cunt[0]
idududu = reaction.message.content.split('?')
peepee = idududu[1]
#await client.send_message(client.get_channel('560678137630031872'), 'test' + peepee)
idud = peepee.split('\nThe events the user has attented before are:')
usid = idud[0]
#await client.send_message(client.get_channel('560678137630031872'), 'test' + usid)
#await client.send_message(client.get_channel('560678137630031872'), 'test' +str(usid))
user=await client.get_user_info(usid)
event = reaction.message.content.split('has attented a ')
eventu = event[1]
evento = eventu.split('Screenshot:')
if reaction.emoji == get(client.get_all_emojis(), name='HYPERS'):
await client.send_message(user, 'Your screenshot has been approved')
await client.delete_message(reaction.message)
async for message in client.logs_from(discord.Object(id='561667365927124992'), limit = 100):
#await client.send_message(user, 'test')
if name in message.content:
if ' eventcode?00' in message.content:
await client.send_message(user, 'You have attented 1 event')
emoji = get(client.get_all_emojis(), name='FeelsBadMan')
await client.add_reaction(message, emoji)
await client.send_message(discord.Object(id='562607755358371840'), str(usid) + ' ' + str(evento[0]))
elif ' eventcode?01' in message.content:
await client.send_message(user, 'You have attented 2 events')
emoji = get(client.get_all_emojis(), name='veetsmug')
await client.add_reaction(message, emoji)
async for message in client.logs_from(discord.Object(id='562607755358371840'), limit = 100):
if usid in message.content:
cont = message.content
await client.edit_message(message, cont + ', ' + str(evento[0]))
elif ' eventcode?10' in message.content:
await client.send_message(user, 'You have attented 3 events')
emoji = get(client.get_all_emojis(), name='POGGERS')
await client.add_reaction(message, emoji)
async for message in client.logs_from(discord.Object(id='562607755358371840'), limit = 100):
if usid in message.content:
cont = message.content
await client.edit_message(message, cont + ', ' + str(evento[0]))
elif ' eventcode?11' in message.content:
emoji = get(client.get_all_emojis(), name='HYPERS')
await client.add_reaction(message, emoji)
async for message in client.logs_from(discord.Object(id='562607755358371840'), limit = 100):
if usid in message.content:
await client.delete_message(message)
elif reaction.emoji == get(client.get_all_emojis(), name='FeelsBadMan'):
await client.send_message(user, 'Your screenshot has not been approved')
await client.delete_message(reaction.message)
#client.event
async def on_message(message):
if message.content == '%start':
if "561047714230435871" in [role.id for role in message.author.roles]:
deadline = datetime.now() + timedelta(days=21)
author = message.author
mes = str(author) + ' has sent an application to become a full fledged FRICK id ='+ str(message.author.id) + ' Deadline+' +str(deadline.strftime("%Y-%m-%d")) + ' eventcode?00'
emoji = get(client.get_all_emojis(), name='HYPERS')
await client.add_reaction(message, emoji)
role = get(message.server.roles, id='561055432748302336')
await client.add_roles(message.author, role)
await client.send_message(client.get_channel('561667365927124992'), mes)
await client.send_message(message.author, '***You have entered the Frickling program!**\n\nTo become a full fledged Frick you must attend 4 guild/alliance events. Please provide screensots to the bot proving that you have attented them by using %attended command followed by a screenshot **LINK** and the name of the activity.\n\n Example: %attented https://cdn.discordapp.com/attachments/530909412320083969/558085258164305921/guild_event_2.jpg fame farm')
role = get(message.server.roles, name='Frickling')
await client.remove_roles(message.author, role)
elif "561055432748302336" in [role.id for role in message.author.roles]:
await client.send_message(message.channel,'Seems like you already started the application process for becoming a full fledged Frick')
else:
await client.send_message(message.channel,'Seems like you do not have the permisssions to use me.\n\nIt might be because your application for Frickling has not yet been approved or you are already a full fledged Frick')
elif message.content == 'Tell that bot to get lost':
if message.author == message.server.get_member('336858563064496130'):
await client.send_message(message.channel,'Get lost, stupid bot')
elif message.content == 'Tell Meatcup to get lost':
if message.author == message.server.get_member('336858563064496130'):
user = discord.utils.get(reaction.message.server.members, id ='331864154803666945')
await client.send_message(user, 'Get lost, Meatcup')
elif message.content == '%cunt':
await client.send_message(message.channel,'Yes, my master?')
emoji = get(client.get_all_emojis(), name='HYPERS')
await client.add_reaction(message, emoji)
elif message.content == '%testfrick':
if "561087733834186754" in [role.id for role in message.author.roles]:
await client.send_message(message.channel,'You are a frick')
else:
await client.send_message(message.channel,'Error')
elif message.content == '%testpend':
if "561055432748302336" in [role.id for role in message.author.roles]:
await client.send_message(message.channel,'You are pending')
else:
await client.send_message(message.channel,'Error')
elif '%attended' in message.content and message.author.id != '560634369094582302':
author = message.author
authid = message.author.id
cunt = 0
msg = message.content.split(' ',2)
if len(msg) > 2:
emoji = get(client.get_all_emojis(), name='HYPERS')
await client.add_reaction(message, emoji)
for i in client.servers:
for x in i.roles:
if x.id == '561055432748302336':
async for message in client.logs_from(discord.Object(id='562607755358371840'), limit = 100):
if authid in message.content:
eventu = message.content.split(' ',1)
cunt = 1
await client.send_message(discord.Object(id='560679934209687552'), str(author) + ' has attented a ' + msg[2] + '\nScreenshot:' + msg[1] + '\nTo approve screenshot react with :HYPERS: to dissaprove react with :FeelsBadMan:\nUserid?'+authid + '\nThe events the user has attented before are: ' + str(eventu[1]))
if cunt == 0:
await client.send_message(discord.Object(id='560679934209687552'), str(author) + ' has attented a ' + msg[2] + '\nScreenshot:' + msg[1] + '\nTo approve screenshot react with :HYPERS: to dissaprove react with :FeelsBadMan:\nUserid?'+ authid)
else:
await client.send_message(message.author,'Error. You did not provide the name of the event or you only provided the name of the event.')
For asynchronous python, when non-blocking sleeping is required, you can use the method asyncio.sleep(n), n being the number of seconds you want the method to sleep for. So a basic async method that sleeps once every 24 hours would look something like this:
async def daily_task():
print('This method will NOT block')
await asyncio.sleep(24*60*60)
EDIT: Thanks go to Benjin, who pointed out that I forgot to await the sleep.
Threads will let you work "simultaneously" on 2 things (or more...). When one thread will sleep, another thread can do "the rest"

Categories

Resources