im making a economy bot like owo but im getting operand errors - discord.py

i cant figure out the error
it just says discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: unsupported operand type(s) for +=: 'int' and 'str'
what can i do here?
here is my code -
import discord
from discord.ext import commands
import json
import random
client = commands.Bot(command_prefix="owo ", intents=discord.Intents.all())
#client.event
async def on_ready():
print("Logged in as {} lets rock!".format(client.user))
#client.command(aliases=['c'])
async def cash(ctx):
await open_account(ctx.author)
user = ctx.author
users = await get_bank_data()
wallet_amt = users[str(user.id)]["wallet"]
await ctx.send(f"<:cowoncy:1048582461610799116> **|** {ctx.author.name} you currently have **__{wallet_amt}__** **cowoncy**!")
# await ctx.send(embed= em)
#client.command(aliases=['sm'])
async def give(ctx,member : discord.Member,amount = None):
await open_account(ctx.author)
await open_account(member)
if amount == None:
await ctx.send(f"🚫 | {ctx.author.name}, Invalid arguments! :c", delete_after=5)
return
bal = await update_bank(ctx.author)
amount = int(amount)
if amount > bal[0]:
await ctx.send(f'🚫 **|** {ctx.author.name}, you silly hooman! You don\'t have enough cowoncy!')
return
await update_bank(ctx.author,-1*amount,'wallet')
await update_bank(member,amount,'wallet')
await ctx.send(f'<:CreditCard:1048583346453757992> **|** **{ctx.author.name}** sent **{amount}')
#client.command(aliases=['d'])
async def add(ctx,member : discord.Member, amount):
await open_account(ctx.author)
await open_account(member)
bal = await update_bank(member)
await update_bank(member, amount,'wallet')
await ctx.send(f'<:CreditCard:1048583346453757992> **|** {member} **{amount}** coins has been added to your balance!')
async def open_account(user):
users = await get_bank_data()
if str(user.id) in users:
return False
else:
users[str(user.id)] = {}
users[str(user.id)]["wallet"] = 0
users[str(user.id)]["bank"] = 0
with open('mainbank.json','w') as f:
json.dump(users,f)
return True
async def get_bank_data():
with open('mainbank.json','r') as f:
users = json.load(f)
return users
async def update_bank(user,change=0,mode = 'wallet'):
users = await get_bank_data()
users[str(user.id)][mode] += change
with open('mainbank.json','w') as f:
json.dump(users,f)
bal = users[str(user.id)]['wallet'],users[str(user.id)]['bank']
return bal
client.run("TOKEN")
i was making a economy bot and i got operand error what can i do here????
any type of help will be appreciated!
also you can dm me here 𓆩†𓆪 𝐌𝐓メ ☯ɪ ᴀᴍ ɢᴏᴋᴜ☯†ᴰᶜ#0001 if you want to ask something about the code...

This is mainly because of your amount argument in the command callback. Since it doesn't have a type annotation (or typehint), it will always be a string.
Lines 62 and 63
users[str(user.id)]["wallet"] = 0
users[str(user.id)]["bank"] = 0
The values you gave them are integers, but the change argument you passed into the update_bank in lines 41, 42, and 51 is a string; you can't add a string to an integer.
This can be fixed by adding int as the type annotation to the argument, so the library will convert the user input into an integer.
Line 26
async def give(ctx,member: discord.Member, amount: int = None):
Line 46
async def add(ctx, member: discord.Member, amount: int):

Related

I need my bot to delete links and videos sent by a certain discord user

I have the link part down but it gives me a 400 Bad Request (error code: 50006): Cannot send an empty message error when i send a link the main problem is that if i try any other methods of writing this code for example i copied some code that deletes all of the messages sent in a chat but it still gives me the same error.
import discord
import responses
async def send_message(message, user_message, is_private):
try:
response = responses.get_response(user_message)
await message.author.send(response) if is_private else await message.channel.send(response)
except Exception as e:
print(e)
def run_discord_bot():
TOKEN = ''
intents = discord.Intents.default()
intents.messages = True
intents.message_content = True
client = discord.Client(intents=intents)
#client.event
async def on_ready():
print(f'{client.user} is now running!')
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.author.id == 0000000000000 and message.startswith("https"):
await message.delete()
# can return here as we deleted message - no need to process anything else
return
username = message.author.name
user_message = message.content
channel = message.channel.name
print(f'{username} said: "{user_message}" ({channel})')
if user_message[0] == '?':
user_message = user_message[1:]
await send_message(message, user_message, is_private=True)
else:
await send_message(message, user_message, is_private=False)
#client.event
async def on_message(message):
if message.author == client.user:
return
username = str(message.author)
user_message = str(message.content)
channel = str(message.channel)
print(f'{username} said: "{user_message}" ({channel})')
if user_message[0] == '?':
user_message = user_message[1:]
await send_message(message, user_message, is_private=True)
else:
await send_message(message, user_message, is_private=False)
client.run('')
Turning my comments into an answer;
Firstly, you need to enable the message_content intent to be able to see message content. You will need to enable the message_content Privileged intent in the Discord developer portal as well.
intents = discord.Intents.default()
intents.messages = True
intents.message_content = True
client = discord.Client(intents=intents)
Then, there should only be one on_message event. But we can merge them.
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.author.id == 0000000000000 and message.startswith("https"):
await message.delete()
# can return here as we deleted message - no need to process anything else
return
username = message.author.name
user_message = message.content
channel = message.channel.name
print(f'{username} said: "{user_message}" ({channel})')
if user_message[0] == '?':
user_message = user_message[1:]
await send_message(message, user_message, is_private=True)
else:
await send_message(message, user_message, is_private=False)
I also changed the user ID to an int - as message.author.id is an int. And changed stop of the str() calls to using the name properties as well.

Change discord.py embed field position

Is it possible to change the position of an embed field in discord.py?
Here is my more detailed problem:
I have an embed, but I have to make it modular, which means that with a command we can either add a field or delete one. The delete command works and the add command works, but now I need to be able to change the position of the field to be the same as the position of the role (because each field corresponds to a role).
How can I do that?
We can't edit embed field's position, but we can try to add every fields in the good ordor so we don't have to edit the field's position !
Here are my codes (working):
import asyncio
import discord
from discord.ext import commands
from datetime import datetime
intents = discord.Intents.all()
bot = commands.Bot(command_prefix = "!1789", help_command = None, intents=intents)
async def get_hour():
now = ""
now = datetime.now()
hour = now.strftime("%H:%M")
return hour
async def role_members_mention(role: discord.Role, emoji):
role_str = ""
if len(role.members):
for member in role.members:
role_str += f"**|** {emoji} **➜** {member.mention}\n"
role_str[:-1]
return role_str
async def soon(role, emoji, max):
soon = f"**|** {emoji} **➜ Soon**\n" * (int(max[role.name].replace("/", "")) - len(role.members))
soon[:-1]
return soon
async def get_all_roles():
guild = bot.get_guild(966749409314504774)
global ceo_aceo_roles_dict
ceo_aceo_roles_dict = {}
ceo = discord.utils.get(guild.roles, id = 966749523949023262)
aceo = discord.utils.get(guild.roles, id = 992137775883243530)
global all_roles_dict
all_roles_dict = {}
all_roles_dict[ceo.position] = ceo
all_roles_dict[aceo.position] = aceo
ceo_aceo_roles_dict[ceo.position] = ceo
ceo_aceo_roles_dict[aceo.position] = aceo
async def update_effective():
ceo_aceo = ""
embed = discord.Embed(title = "**E͟͟͟F͟͟͟F͟͟͟E͟͟͟C͟͟͟T͟͟͟I͟͟͟F͟͟͟ S͟͟͟T͟͟͟A͟͟͟F͟͟͟F͟͟͟**. <:3446blurplecertifiedmoderator:1001403463214825542>", description = "", color = 0x000000)
max = {}
total = {}
effectif_staff_emojis = ["<:adcrown:1001400557073866762>", "<:bluesettings:1001472768161894532>", "<:diplome:1001472522811883621>", "<:5961blurpleemployee:1001403806828994570>"]
roles_staff_emojis = ["<:5961blurpleemployee:1001403806828994570>", "<:Dev:1001412860091580487>", "<:direction:1001476149051924591>", "<:bluevoicechannel:1001473637091659836", "<:direction:1001476149051924591>", "<:spideyn7:996331019735158864>", "<:logo_twitch:1005196891010629702>"]
all_roles = sorted(all_roles_dict)
ceo_aceo_roles = sorted(ceo_aceo_roles_dict)
all_roles.reverse()
ceo_aceo_roles.reverse()
x = -1
for role in all_roles:
x += 1
all_roles[x] = all_roles_dict[role]
x = -1
for role in ceo_aceo_roles:
x += 1
ceo_aceo_roles[x] = ceo_aceo_roles_dict[role]
for role in all_roles:
number = 0
for car in role.name:
if car == "‎":
number += 1
max[role.name] = "/" + str(number)
if len(role.members) >= int(max[role.name].replace("/", "")):
total[role.name] = f"🔒 **{str(len(role.members))} {max[role.name]}**"
else:
total[role.name] = f"🔓 **{str(len(role.members))} {max[role.name]}**"
message = await (await get_effective_staff_channel()).fetch_message(1059250505689337998)
for role in ceo_aceo_roles:
ceo_aceo += f"{role.mention} {total[role.name]}\n{await role_members_mention(role, effectif_staff_emojis[0])}{await soon(role, effectif_staff_emojis[0], max)}\n\n"
embed.add_field(name = "**C.E.O & A.C.E.O** <:adcrown:1001400557073866762>", value = ceo_aceo, inline = False)
embed.set_thumbnail(url = "https://media.discordapp.net/attachments/1001404772496187392/1059246720669733014/Picsart_22-10-19_21-20-35-971.jpg?width=1326&height=529")
embed.set_image(url = "https://media.discordapp.net/attachments/1001404772496187392/1059246720875241542/Picsart_22-10-13_21-14-41-363.jpg?width=618&height=618")
await message.edit(embed = embed)
async def delete_messages(ctx, number_of_message_to_delete = 1, time_to_wait = 0):
await asyncio.sleep(time_to_wait)
await ctx.channel.purge(limit=number_of_message_to_delete)
#bot.event
async def on_ready():
print(f"[{await get_hour()}] Ready !\n Username: {bot.user.name}\n----------------------------------------------------")
await get_all_roles()
await update_effective()
while True:
await asyncio.sleep(600)
await update_effective()
#bot.command()
#commands.has_permissions(administrator = True)
async def addeffectifstaff(ctx, role: discord.Role, number = 1):
await delete_messages(ctx)
role = discord.utils.get(ctx.guild.roles, id = role.id)
if role in all_roles_dict.values():
await ctx.send("Désolé mais ce rôle est déjà dans l'effectif.")
else:
ceo_aceo_roles_dict[role.position] = role
all_roles_dict[role.position] = role
await update_effective()
await ctx.send(f"Bien ! Le rôle {role.name} a été ajouté à l'effectif !")
await delete_messages(ctx, 1, 3)
print(f'[{await get_hour()}] {ctx.author.name} used the command "addeffectifstaff" to make me add the role "{role.name}" to the effective message.')
#bot.command()
#commands.has_permissions(administrator = True)
async def deleffectif(ctx, role: discord.Role):
await delete_messages(ctx)
role = discord.utils.get(ctx.guild.roles, id = role.id)
if not role in all_roles_dict.values():
await ctx.send("Désolé mais ce rôle n'est déjà pas dans l'effectif.")
else:
ceo_aceo_roles_dict.pop(role.position)
all_roles_dict.pop(role.position)
await update_effective()
await ctx.send(f"Bien ! Le rôle {role.name} a été supprimé de l'effectif !")
await delete_messages(ctx, 1, 3)
print(f'[{await get_hour()}] {ctx.author.name} used the command "deleffectif" to make me remove the role "{role.name}" to the effective message.')
bot.run(token)

Discord.py unban not working. No mistakes shown discord.py 2.0.1, Python 3.10

Tried everything I found here. No mistakes shown, unban just not working. discord.py 2.0.1, Python 3.10
Ban is working fine, but when I want to unban it's doing nothing. Nothing on console, nothing happening
#client.command()
#commands.has_permissions(ban_members = True)
#commands.has_permissions(administrator = True)
async def ban(ctx, member : discord.Member, *, reason = None):
await member.ban(reason = reason)
#unban
#client.command()
#commands.has_permissions(administrator = True)
async def unban(ctx, *, 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'Unbanned {user.mention}')
return'
In the version of discord.py you're using you must not use await for ctx.guild.bans() and you must also add an async at for ban_entry in banned_users:.
You also need to remove your ' after the return on the last line
Example:
#client.command()
#commands.has_permissions(administrator = True)
async def unban(ctx: commands.Context, *, member):
banned_users = ctx.guild.bans()
member_name, member_discriminator = member.split("#")
async 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'Unbanned {user.mention}')
return

Problem making a discord reaction role bot in discord

So im currently making a discord bot that give a specific role to who ever react to the message i encountered some problems i can't fix my self
#client.event
async def on_ready():
Channel = client.get_channel('904620745462804520')
Text= "React to get Verified!"
Moji = await client.send_message(Channel, Text)
await client.add_reaction(Moji, emoji='✅')
#client.event
async def on_reaction_add(reaction, user):
Channel = client.get_channel('904620745462804520')
if reaction.message.channel.id != Channel:
return
if reaction.emoji == "✅":
Role = discord.utils.get(user.server.roles, name="Verified")
await client.add_roles(user, Role)
Please, read documentation carefully
#client.event
async def on_ready():
Channel = client.get_channel('904620745462804520')
Text = "React to get Verified!"
Moji = await Channel.send(Text)
await Moji.add_reaction(emoji='✅')
#client.event
async def on_reaction_add(reaction, user):
if reaction.message.channel.id != '904620745462804520' or user == client.user:
return
if reaction.emoji == "✅":
guild = await client.fetch_guild('GUILD_ID_HERE')
Role = discord.utils.get(guild.roles, name="Verified")
await user.add_roles(Role)

How do I lower case the response discord.py

So basicly the person is trying to guess whats the name of the anime! What I want it to do is to ingore the case sentativity! How can I do that? Here is the code:
#client.command()
async def work(ctx):
await open_account(ctx.author)
users = await get_bank_data()
user = ctx.author
def check(m):
return m.author.id == ctx.author.id
Question1 = 'https://upload.wikimedia.org/wikipedia/en/thumb/d/dc/DARLING_in_the_FRANXX%2C_second_key_visual.jpg/220px-DARLING_in_the_FRANXX%2C_second_key_visual.jpg'
Question2 = 'http://www.j1studios.com/wordpress/wp-content/uploads/Trinity-Seven-Header-001-20160707.jpg'
Question3 = 'https://www.animenewsnetwork.com/hotlink/images/encyc/A18170-2511174083.1466822675.jpg'
Question4 = 'https://www.animenewsnetwork.com/hotlink/images/encyc/A16344-911899268.1425205899.jpg'
Question5 = 'https://www.theanimedaily.com/wp-content/uploads/2020/06/20061004422210.jpg'
Question6 = 'https://th.bing.com/th/id/OIP.zvtbvP4JZNrrlAKPnclMpwHaEK?pid=Api&rs=1&adlt=strict'
Question7 = 'https://mangathrill.com/wp-content/uploads/2020/01/pjimage-1-4.jpg'
Question8 = 'https://th.bing.com/th/id/OIP.xV_2srfdOhEre9Vua-u6zAHaFb?pid=Api&rs=1&adlt=strict'
Question9 = 'https://img1.looper.com/img/gallery/the-untold-truth-of-hunter-x-hunter/intro-1591800144.jpg'
Question10 = 'https://i1.wp.com/static.anidub.com/blog/2014/09/Seirei-Tsukai-no-Blade-Dance.jpg'
questionlist = [Question1, Question2, Question3, Question4, Question5, Question6, Question7, Question8, Question9, Question10]
question = random.choice(questionlist)
await ctx.send("What is the title name of this anime?")
await asyncio.sleep(1)
await ctx.send(question)
msg = await client.wait_for('message', check=check)
await msg.lower()
if question == Question1:
if msg.content == "darling in the franxx":
earnings = random.randrange(300, 500)
await ctx.send(f"You did good! You got an earning of **{earnings}** coins!")
else:
earnings = random.randrange(0, 200)
await ctx.send(f"Did you even try? You got **{earnings}** coins!")
msg = await client.wait_for('message', check=check) returns you the discord.Message class. And discord.Message has no attribute lower(). But it has content, content returns the string value of the message.
And also await msg.lower() is a weird usage, it's not a coroutine so you can't await it.
So you can simply do:
msg = await client.wait_for('message', check=check)
msg_content = msg.content.lower()
if question == Question1:
if msg_content == "darling in the franxx":
earnings = random.randrange(300, 500)
await ctx.send(f"You did good! You got an earning of **{earnings}** coins!")
else:
earnings = random.randrange(0, 200)
await ctx.send(f"Did you even try? You got **{earnings}** coins!")
And also, I suggest you to put questions and question list out of the command, it becomes more optimized.

Resources