(CLOSED) Bot doesnt send anything, and doesnt give an error - discord

I have this code:
#rob
#client.command()
#commands.cooldown(1,10800,commands.BucketType.user)
async def rob(ctx,member:discord.User = None):
if member == None:
em = discord.Embed(title='ERROR:', description='Please specify a member you want to rob!', color=0xff0000)
await ctx.send(embed = em)
return
await open_account(ctx.author)
await open_account(member)
bal = await update_bank(member)
if bal[0]<50:
em = discord.Embed(title='ERROR:', description="The member you try to rob doesn't have that much money!", color=0xff0000)
await ctx.send(embed = em)
return
if amount<0:
em = discord.Embed(title='ERROR:', description="Amount must be positive!", color=0xff0000)
await ctx.send(embed = em)
return
earnings = random.randrange(0, bal[100])
fine = random.randrange(0, bal[100])
em1 = discord.Embed(title='Succesfully robbed!', description=f"You robbed {earnings} coins!", color=0x00ff00)
em2 = discord.Embed(title='Caught!', description=f"You got caught! You paid a {fine} coins fine! ", color=0x00ff00)
yesorno = random.randrange(0, 1)
if yesorno == 1:
await ctx.send(embed = em1)
await update_bank(ctx.author,earnings)
await update_bank(member,-1*earnings)
else:
await ctx.send(embed = em2)
await update_bank(ctx.author,-1*fine)
This function's goal is to rob someone and take their money or give them a fine, but it doesn't work. It doesn't send em1 or em2, I don't know how to fix it. I tried many things, but it doesn't give an error!

What fixed it for me was changing the yesorno function. Changed it to:
yesorno = random.randrange(0, 2)
if yesorno == 1:
await ctx.send(embed = em1)
await update_bank(ctx.author,1*earnings)
await update_bank(member,-1*earnings)
else:
await ctx.send(embed = em2)
await update_bank(ctx.author,-1*fine)
await update_bank(member,1*fine)

Related

Discord bot leave and play again something error

I have a problem. This discord bot can join, play music, pause resune and leave. When i run the bot it can play songs but when i tell him to leave, join again and play something i get this error: discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ClientException: Not connected to voice.
music = DiscordUtils.Music()
#client.command(pass_context = True)
async def play(ctx,*,url):
player = music.get_player(guild_id = ctx.guild.id)
if not player:
player = music.create_player(ctx, ffmpeg_error_betterfix = True)
if not ctx.voice_client.is_playing():
await player.queue(url, search = True)
song = await player.play()
else:
song = await player.queue(url, search = True)
#client.command(pass_context = True)
async def pause(ctx):
player = music.get_player(guild_id = ctx.guild.id)
song = await player.pause()
#client.command(pass_context = True)
async def join(ctx):
channel = ctx.message.author.voice.channel
voice = await channel.connect()
#client.command(pass_context = True)
async def resume(ctx):
player = music.get_player(guild_id = ctx.guild.id)
song = await player.resume()
#client.command(pass_context = True)
async def queue(ctx):
player = music.get_player(guild_id = ctx.guild.id)
#client.command(pass_context = True)
async def leave(ctx):
await ctx.voice_client.disconnect()

2 numbers not adding together correctly

I'm using repl.it database for a discord economy bot that i'm making. I made a withdraw command, but when I type !withdraw 10 I'm expecting to receive currentbalance + amount (like if current balance is 50 and i typed !with 100 I should get 150) but I keep getting "50100". Here is my code:
if (message.content.toLowerCase().startsWith("#ايداع")) {
const args = message.content.trim().split(/ +/g);
let money = await db.get(`wallet_${message.member}`)
let currentbalance1 = await db.get(`wallet_${message.member}`)
let currentbalance = await db.get(`bank_${message.member}`)
let gembed = new Discord.MessageEmbed()
.setColor("RED")
.setDescription("ليس لديك مبلغ كافي للايداع")
let cembed = new Discord.MessageEmbed()
.setColor("RED")
.setDescription("يرجى تحديد مبلغ للايداع");
let amount = args[1];
if (!amount || isNaN(amount))
return message.reply(cembed);
await db.set(`bank_${message.member}`, currentbalance + amount);
await db.set(`wallet_${message.member}`, currentbalance1 - amount)
let sembed = new Discord.MessageEmbed()
.setColor("RED")
.setDescription("لقد قمت بايداع" + amount + "الى حسابك البنكي");
message.channel.send(sembed);
}
If your output is 50100 from 50 + 100 it means that your numbers (50 and 100) are strings not numbers. A simple solution would be to use parseInt.
Example:
let currentbalance1 = await db.get(`wallet_${message.member}`);
let currentbalance = await db.get(`bank_${message.member}`);
await db.set(`bank_${message.member}`, parseInt(currentbalance) + parseInt(amount));
await db.set(`wallet_${message.member}`, parseInt(currentbalance1) - parseInt(amount));
Full example:
if (message.content.toLowerCase().startsWith("#ايداع")) {
const args = message.content.trim().split(/ +/g);
let money = await db.get(`wallet_${message.member}`)
let currentbalance1 = await db.get(`wallet_${message.member}`)
let currentbalance = await db.get(`bank_${message.member}`)
let gembed = new Discord.MessageEmbed()
.setColor("RED")
.setDescription("ليس لديك مبلغ كافي للايداع")
let cembed = new Discord.MessageEmbed()
.setColor("RED")
.setDescription("يرجى تحديد مبلغ للايداع");
let amount = args[1];
if (!amount || isNaN(amount)) return message.reply(cembed);
await db.set(`bank_${message.member}`, parseInt(currentbalance) + parseInt(amount));
await db.set(`wallet_${message.member}`, parseInt(currentbalance1) - parseInt(amount))
let sembed = new Discord.MessageEmbed()
.setColor("RED")
.setDescription("لقد قمت بايداع" + amount + "الى حسابك البنكي");
message.channel.send(sembed);
}

Discord.py snipe command is sniping messages from other channels

I recently made a snipe command for my discord bot but I have one problem. Snipe command snipes a message from other channels when I for example want to snipe a message in general. Here is my code:
#bot.event
async def on_message_delete(message):
if message.attachments:
bob = message.attachments[0]
bot.sniped_messages[message.guild.id] = (bob.proxy_url, message.content, message.author, message.channel.name, message.created_at)
else:
bot.sniped_messages[message.guild.id] = (message.content,message.author, message.channel.name, message.created_at)
#bot.command(aliases=['s'])
async def snipe(ctx):
try:
bob_proxy_url, contents,author, channel_name, time = bot.sniped_messages[ctx.guild.id]
except:
contents,author, channel_name, time = bot.sniped_messages[ctx.guild.id]
try:
embed = discord.Embed(description=contents , color=discord.Color.purple(), timestamp=time)
embed.set_image(url=bob_proxy_url)
embed.set_author(name=f"{author.name}#{author.discriminator}", icon_url=author.avatar_url)
embed.set_footer(text=f"Deleted in : #{channel_name}")
await ctx.channel.send(embed=embed)
except:
embed = discord.Embed(description=contents , color=discord.Color.purple(), timestamp=time)
embed.set_author(name=f"{author.name}#{author.discriminator}", icon_url=author.avatar_url)
embed.set_footer(text=f"Deleted in : #{channel_name}")
await ctx.channel.send(embed=embed)
snipe_message_author = {}
snipe_message_content = {}
#client.event
async def on_message_delete(message):
snipe_message_author[message.channel.id] = message.author
snipe_message_content[message.channel.id] = message.content
#client.command(name = 'snipe')
async def snipe(ctx):
channel = ctx.channel
try:
em = discord.Embed(description = f"`{snipe_message_content[channel.id]}`\nMessage sent by {snipe_message_author[channel.id]}!", color = 0x00c230)
em.set_author(name = f"Last deleted message in #{channel.name}")
em.set_thumbnail(url="https://cdn.discordapp.com/avatars/352793093105254402/8a2018de21ad29973696bfbf92fc31cd.png?size=4096")
em.set_footer(text = f"Snipe requested by {ctx.message.author}")
await ctx.send(embed = em)
except:
embed = discord.Embed(colour = 0x00c230)
embed.set_author(name=f"There are no deleted messages in #{ctx.channel}!")
embed.set_thumbnail(url="https://cdn.discordapp.com/avatars/352793093105254402/8a2018de21ad29973696bfbf92fc31cd.png?size=4096")
embed.set_footer(text=f"Snipe requested by {ctx.message.author}")
await ctx.channel.send(embed=embed)
Thats what I use and it works properly.
Since I added [message.channel.id] to the variables it only checks for snipes in that channel. This is how it looks like in Discord

Getting multiple users to guess the number discord.py

#commands.command()
async def gtn(self, ctx):
for guess in range(0, 5):
await ctx.send('guess')
number = random.randint(1,10)
response = await self.client.wait_for('message')
guess = int(response.content)
if guess == number:
await ctx.send('correct')
So this is my code, I want multiple users to guess the number and have unlimited chances but I'm not too sure how to do so.
You can use a while loop
#commands.command()
async def gtn(self, ctx):
while True:
await ctx.send('guess')
number = random.randint(1,10)
response = await self.client.wait_for('message')
guess = int(response.content)
if guess == number:
await ctx.send('correct')
break

Poll question which adds the correct amount of reactions. (d.py)

I am trying to make a poll command which adds the correct amount of reactions such as A B C D E etc.
I have already tried this but it was a simple yes or no poll command.
elif message.content.startswith('m/qpoll'):
question = message[8:]
await message.delete()
message = await message.channel.send(f"**New poll:** {question}")
await message.add_reaction('❌')
await message.add_reaction('✔️')
What i am trying to achieve is a command which adds A B C reactions if there is three possible answers and A B C D E if there is five possible answers etc.
The command the user has to use is preferred to be in this format:
m/poll "question" "answer 1" "answer 2" "answer 3"
The command needs to be under a on_message statement as the command package does not work as well for my bot.
A simple way to do it, without using discord.ext.commands :
elif message.content.startswith('m/qpoll'):
content = message.content[8:]
items = content.split(" ")
question = items[0]
answers = '\n'.join(items[1:])
await message.delete()
message = await message.channel.send(f"**New poll:** {question}\n{answers}")
reactions = ['A', 'B', 'C', 'D', 'E'] #replace the letters with your reactions
for i in range(len(items[1:]))
await message.add_reaction(reactions[i])
Here's the poll command I made for my bot
#commands.command()
async def poll(self, ctx):
"""
Conduct a poll (interactive)
?poll
"""
member = ctx.author
member: Member
maker = []
await ctx.send("```What is the Question ❓```")
em = ["🧪", "🧬", "🚀", "🖌️", "🧨"]
def mcheck(m):
return m.author == member
try:
msg = await self.bot.wait_for('message', timeout=20.0, check=mcheck)
maker.append(msg.content)
except TimeoutError:
return await ctx.send("```Poll timed out ⏳```")
await ctx.send("```How many options do you want?```")
try:
msg = await self.bot.wait_for('message', timeout=20.0, check=mcheck)
except TimeoutError:
return await ctx.send("```Poll timed out ⏳```")
i = int(msg.content)
if i > 5:
return await ctx.send("```A maximum of 5 options for polls```")
await ctx.send("```Enter your options ✔```")
for i in range(i):
try:
await ctx.send(f"```{i + 1}) ```")
msg = await self.bot.wait_for('message', timeout=20.0, check=mcheck)
maker.append(msg.content)
await msg.add_reaction("✅")
except TimeoutError:
return await ctx.send("```Poll timed out ⏳```")
poller = Embed(color=0x5EE34)
poller.title = maker[0]
des = ''
for j in range(1, len(maker)):
des += f"```{em[j - 1]} {maker[j]}```\n"
poller.description = des
pr = await ctx.send(embed=poller)
for j in range(i + 1):
await pr.add_reaction(em[j])
def reac_check(r, u):
return pr.id == r.message.id and r.emoji in em
eopt = {e: 0 for e in em}
while True:
try:
reaction, user = await self.bot.wait_for('reaction_add', timeout=20.0, check=reac_check)
e = str(reaction.emoji)
except TimeoutError:
await ctx.send("```Poll Finished ✅```")
break
if e in eopt.keys() and user != self.bot.user:
eopt[e] += 1
eopt = {k: v for k, v in sorted(eopt.items(), key=lambda item: item[1], reverse=True)}
most = next(iter(eopt))
loc = em.index(most)
poller.title = "Results 🏆"
poller.description = f"```Folks chose 📜\n{maker[loc + 1]}```"
return await ctx.send(embed=poller)
As a rule of thumb avoid using on_message to create commands. You can read about commands.Bot() in the docs.
That said you should be able adapt the above example to suit your needs.

Resources