Discord.py V2 Giveaway Command Not Working - python

I am making a discord.py giveaway command. It puts the winners into the list 'winners' and then it's supposed to announce them. My issue is that I can print the winners to the terminal but I can't get the bot to mention the winners in the message it sends.
This is the code I am using:
#commands.hybrid_command(name='startgive')
#commands.has_permissions(administrator=True)
async def startgive(self, ctx: commands.Context, prize: str, duration: str, total_winners: int, *, channel: discord.TextChannel):
await ctx.send(f"Giveaway created in <#{channel.id}> for {prize}, and will last {duration}.")
duration_seconds = convert(duration)
embed = discord.Embed(title = f"{prize} Giveaway!", color = ctx.author.color)
embed.add_field(name='Ends', value=f"{duration}", inline = False)
embed.add_field(name = "Hosted by:", value = ctx.author.mention, inline = False)
embed.add_field(name='Winners', value=f"{total_winners}", inline = False)
my_msg = await channel.send(embed = embed)
await my_msg.add_reaction("🎉")
await asyncio.sleep(duration_seconds)
new_msg = await channel.fetch_message(my_msg.id)
users = []
for reaction in new_msg.reactions:
if reaction.emoji == '🎉':
async for user in reaction.users():
if user != self.bot.user:
users.append(user.mention)
if len(users) < total_winners:
winners_number = len(users)
else:
winners_number = total_winners
winners = []
for i in range(winners_number):
user = random.randint(0, winners_number)
if users[user] not in winners:
winners.append(users[user])
print(', '.join(winners)) #This line is used to simply show that the winners array does hold a value of a user being mentioned
updatedEmbed = discord.Embed(title = f"{prize} Giveaway!", color = ctx.author.color)
updatedEmbed.add_field(name = "Hosted by:", value = ctx.author.mention, inline = False)
updatedEmbed.add_field(name = "Winners:", value = f"{', '.join(winners)}", inline = False)
updatedEmbed.set_footer(text = f"Ended", inline = False)
await my_msg.edit(embed=updatedEmbed)
await channel.send(f"Congratulations! {', '.join(winners)} won {prize}! Thank you for participating.")
def convert(time):
pos = ["s","m","h","d"]
time_dict = {"s" : 1, "m" : 60, "h" : 3600 , "d" : 3600*24}
unit = time[-1]
if unit not in pos:
return -1
try:
val = int(time[:-1])
except:
return -2
return val * time_dict[unit]

Related

I am trying to make a use system for my discord bot (py), but it does not work

I am trying to make an economy system for my discord servers with discord.py but I cannot find any system to use an object which is stored in an inventory in .JSON. I would like that when we call the function use, for example, it removes an object from my inventory, and if this object is not in my inventory, it tells me that I do not have it.
My code:
#bot.command()
async def use(ctx, item, amount = -1,):
await open_account(ctx.author)
res = await use_this(ctx.author,item,amount)
if item <= 0 in
if not res[0]:
if res[1]==1:
await ctx.send("That Object isn't there!")
return
if res[1]==2:
await ctx.send(f"Vous n'avez pas cette objet{amount} {item}")
return
await ctx.send(f"You use 1 {item}")
async def use_this(user,item_name,amount):
item_name = item_name.lower()
name_ = None
for item in mainshop:
name = item["name"].lower()
if name == item_name:
name_ = name
price = item["price"]
break
if name_ == None:
return [False,1]
cost = price*amount
users = await get_bank_data()
bal = await update_bank(user)
if bal[0]<cost:
return [False,2]
try:
index = 0
t = None
for thing in users[str(user.id)]["inv"]:
n = thing["item"]
if n == item_name:
old_amt = thing["amount"]
new_amt = old_amt + amount
users[str(user.id)]["inv"][index]["amount"] = new_amt
t = 1
break
index+=1
if t == None:
obj = {"item":item_name , "amount" : amount}
users[str(user.id)]["inv"].append(obj)
except:
obj = {"item":item_name , "amount" : amount}
users[str(user.id)]["inv"] = [obj]
with open("mainbank.json","w") as f:
json.dump(users,f)
return [True,"Worked"]

why does it keep saying "TypeError: '<=' not supported between instances of 'int' and 'str'"?

this is the full error of the code
i would really love the help
mainshop = [{"name":"Time_watch","price":1000,"description":"Resets certain cooldowns (limited uses)(WIP)"}, {"name":"Gun","price":10000,"description":"A better way to rob people with a shorter cooldown!"}, {"name":"Guhhh Placeholder!!","price":10000000,"description":"I sure love placeholders"}]
#client.command()
#commands.is_owner()
async def shop(ctx):#real#:troll:.name
em = discord.Embed(title = "Shopping District")
for item in mainshop:
name = item["name"]
price = item["price"]
desc = item["description"] #i do believe its because you have like no DESCRIPTION in the item list thing
#get fake
em.add_field(name = name, value = f"${price} | {desc}")
#real
await ctx.send(embed = em)
import discord
from discord.ext import commands
import asyncio
import os
import json
##### START LEVEL COMMAND #####
#client.command(name='bal')
async def balance(ctx, user:discord.Member=None):
colour = randint(0, 0xffffff)
await open_account(ctx.author)
if user is None:
user = ctx.author
users = await get_bank_data()
wallet_amt = users[str(user.id)]["wallet"]
bank_amt = users[str(user.id)]["bank"]
em = discord.Embed(title=f"{user}'s balance", color=colour)
em.add_field(name="Wallet", value=wallet_amt)
em.add_field(name="Bank", value=bank_amt)
await ctx.send(embed=em)
async def buy_this(user,item_name,amount):
item_name = item_name.lower()
name_ = None
for item in mainshop:
name = item["name"].lower()
if name == item_name:
name_ = name
price = item["price"]
break
if name_ == None:
return [False,1]
cost = price*amount
users = await get_bank_data()
bal = await update_bank(user)#r.i.p. KB's confindince
if bal[0]<= cost:
return [False,2]
try:
index = 0
t = None
for thing in users[str(user.id)]["bag"]:
n = thing["item"]
if n == item_name:
old_amt = thing["amount"]
new_amt = old_amt + amount
users[str(user.id)]["bag"][index]["amount"] = new_amt
t = 1
break
index+=1
if t == None:
obj = {"item":item_name , "amount" : amount}
users[str(user.id)]["bag"].append(obj)
except:
obj = {"item":item_name , "amount" : amount}
users[str(user.id)]["bag"] = [obj]
with open("mainbank.json","w") as f:
json.dump(users,f)
await update_bank(user,cost*-1,"wallet")
return [True,"Worked"]
#client.command()
async def buy(ctx,item,amount):#how come these arent definded no more? oh I prollydid smth by mistake guhhhhhhh
res = await buy_this(ctx.author,item,amount)
if not res[0]:
if res[1]==1:
await ctx.send("That is not an item in shop")
return
if res[1]==2:
await ctx.send(f"You don't have enough money to buy the {amount}")
return
await ctx.send(f"Successfully bought {amount}: {item}")
#client.command()
#commands.is_owner()
async def bag(ctx):
await open_account(ctx.author)
user = ctx.author
users = await get_bank_data()
try:
bag = users[str(user.id)]["bag"]
except:
bag = []
em = discord.Embed(title = "Bag")
for item in bag:
name = item["item"]
amount = item["amount"]
em.add_field(name = name, value = amount)
await ctx.send(embed = em)
#Oh you mean this ? oh yeah Idk what I put that there
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
the code that should matter. I do not understand at all what is wrong with the code. I used this code before no errors. So if anyone could please explain that would be greatly appreciated. I have tried putting this in its own thing. it didnt work still. i have also tried putting if bal <= int(cost) this also didnt work.
on the line if bal[0]<= cost: if you cast to an integer int(bal[0]) it should be comparing two integers then, and vice-versa if cost is a string
Cost is already an int, looks like bal[0] is a string. Try int(bal[0]) <= cost instead (or float(bal[0]) if it has decimals)

How to let the bot delete your command after it reply me in python

I am doing a giveaway command call =gstart <time> <prize and the giveaway will be held in the channel I use this command and After sending the embed giveaway message it will delete the gstart command. Here is the code:
#bot.command()
async def gstart(ctx,time,*,prize):
time = convert(time)
if time == -1:
await ctx.send("Error, can't identify time unit")
if time == -2:
await ctx.send("Error, can't identify time value")
embed = discord.Embed(title=prize, description = f"React with :tada: to enter\nHosted by: {ctx.author.mention}", color=discord.Color.red())
embed.set_footer(text = f"Ends at {time} from now!")
#delete-command
await ctx.send(":tada: **GIVEAWAY** :tada:")
my_msg = await ctx.send(embed = embed)
await my_msg.add_reaction("🎉")
await asyncio.sleep(time)
new_msg = await ctx.fetch_message(my_msg.id)
users = await new_msg.reactions[0].users().flatten()
users.pop(users.index(bot.user))
winner = random.choice(users)
await ctx.send(f"Congratulations {winner.mention}! You won the {prize}!")
msg_link = my_msg.jump_url
winner_embed = discord.Embed(title=f"Hey {winner}",description=f"You just won a [giveaway]({msg_link}) in {ctx.guild}",color=discord.Color.red())
winner_embed.add_field(name=prize,value=f"Hosted by: {ctx.author.mention}",inline=True)
await winner.send(embed=winner_embed)
By the way the convert() function looks like this:
def convert(time):
pos = ["s","m","h","d"]
time_dict = {"s" : 1, "m" : 60, "h" : 3600, "d" : 3600*24}
unit = time[-1]
if unit not in pos:
return -1
try:
val = int(time[:-1])
except:
return -2
return val * time_dict[unit]
Reply you with the discord.Context object and delete the message user sent.
Example:
import asyncio
#bot.command()
async def deleteCommandAfterSent(ctx):
await ctx.send("blablabla ") #REPLY MESSAGE
await asyncio.sleep(1)
await ctx.message.delete()

Giveaway command time converting error Discord.Py

Here is the code I have, the time is not being converted, and I don't know what to do anymore. If you know what to do, let me know how to do this
Here is what I got so far:
def convert(time):
pos = ["s","m","h","d"]
time_dict = {"s" : 1, "m" : 60, "h" : 3600, "d": 3600*24}
unit = time[-1]
if unit not in pos:
return -1
try:
val = int(time[:-1])
except:
return -2
return val * time_dict[unit]
#---------------------------------------------------------------------------
#client.command()
#commands.has_permissions(manage_messages = True)
async def giveaway(ctx, time : str, *, prize: str):
embed = discord.Embed(title=prize,
description=f"Hosted by - {ctx.author.mention}\nReact with :tada: to enter!\nTime Remaining: **{time}** seconds",
color=ctx.guild.me.top_role.color, )
msg = await ctx.channel.send(content=":tada: **GIVEAWAY** :tada:", embed=embed)
await msg.add_reaction("🎉")
await asyncio.sleep(3)
new_msg = await ctx.channel.fetch_message(msg.id)
user_list = [u for u in await new_msg.reactions[0].users().flatten() if u != client.user] # Check the reactions/don't count the bot reaction
if len(user_list) == 0:
await ctx.send("No one reacted.")
else:
winner = random.choice(user_list)
await ctx.send(f"{winner.mention} You have won the {prize}!")
When I type in 2m meaning 2 minutes, it shows 2m seconds remaining, now I know why it says seconds because I have not updated the response yet, but the time is only 2 seconds plus the 3 seconds delay time. Basically a total of around 6 seconds.
I did just throw 2 commands from stack overflow together, and it is like putting in a Lamborghini head gasket and a dodge engine block, I know it should not work, even with the little bit of modifications, I kinda do see whats wrong now, but I don't know how to fix it
So I revised your code and changed the giveaway command a little bit. After a few modifications, the command worked as it should for me. Here is how I re-defined it:
def convert(time):
pos = ["s", "m", "h", "d"]
time_dict = {"s": 1, "m": 60, "h": 3600, "d": 3600 * 24}
unit = time[-1]
if unit not in pos:
return -1
try:
val = int(time[:-1])
except:
return -2
return val * time_dict[unit]
# ---------------------------------------------------------------------------
#client.command()
#commands.has_permissions(manage_messages=True)
async def giveaway(ctx, time: str, *, prize: str):
time = convert(time)
embed = discord.Embed(title=prize,
description=f"Hosted by - {ctx.author.mention}\nReact with :tada: to enter!\nTime Remaining: **{time}** seconds",
color=ctx.guild.me.top_role.color)
msg = await ctx.channel.send(content=":tada: **GIVEAWAY** :tada:", embed=embed)
await msg.add_reaction("🎉")
await asyncio.sleep(3)
await asyncio.sleep(int(time))
new_msg = await ctx.channel.fetch_message(msg.id)
user_list = [user for user in await new_msg.reactions[0].users().flatten() if
user != client.user] # Check the reactions/don't count the bot reaction
if len(user_list) == 0:
await ctx.send("No one reacted.")
else:
winner = random.choice(user_list)
await ctx.send(f"{winner.mention} You have won the {prize}!")
You can use this for converting time.
import re
from discord.ext.commands import BadArgument
time_regex = re.compile(r"(?:(\d{1,5})(h|s|m|d))+?")
time_dict = {"h": 3600, "s": 1, "m": 60, "d": 86400}
def convert(argument):
args = argument.lower()
matches = re.findall(time_regex, args)
time = 0
for key, value in matches:
try:
time += time_dict[value] * float(key)
except:
raise BadArgument
return round(time)

How to make a leaderboard command discord.py?

I have looked all over the web, and couldn't find an answer. I also asked my friend but he didn't know how to do this command. How can I make this level code display in a leaderboard command?
Here is my code:
#client.event
async def on_message(message):
if not message.author.bot:
print('function load')
with open('level.json','r') as f:
users = json.load(f)
print('file load')
await update_data(users, message.author,message.guild)
await add_experience(users, message.author, 4, message.guild)
await level_up(users, message.author,message.channel, message.guild)
with open('level.json','w') as f:
json.dump(users, f)
await client.process_commands(message)
async def update_data(users, user,server):
if not str(server.id) in users:
users[str(server.id)] = {}
if not str(user.id) in users[str(server.id)]:
users[str(server.id)][str(user.id)] = {}
users[str(server.id)][str(user.id)]['experience'] = 0
users[str(server.id)][str(user.id)]['level'] = 1
elif not str(user.id) in users[str(server.id)]:
users[str(server.id)][str(user.id)] = {}
users[str(server.id)][str(user.id)]['experience'] = 0
users[str(server.id)][str(user.id)]['level'] = 1
async def add_experience(users, user, exp, server):
users[str(user.guild.id)][str(user.id)]['experience'] += exp
async def level_up(users, user, channel, server):
experience = users[str(user.guild.id)][str(user.id)]['experience']
lvl_start = users[str(user.guild.id)][str(user.id)]['level']
lvl_end = int(experience ** (1/4))
if str(user.guild.id) != '757383943116030074':
if lvl_start < lvl_end:
await channel.send('{} has leveled up to Level {}'.format(user.mention, lvl_end))
users[str(user.guild.id)][str(user.id)]['level'] = lvl_end
#client.command(aliases = ['rank','lvl'])
async def level(ctx,member: discord.Member = None):
if not member:
user = ctx.message.author
with open('level.json','r') as f:
users = json.load(f)
lvl = users[str(ctx.guild.id)][str(user.id)]['level']
exp = users[str(ctx.guild.id)][str(user.id)]['experience']
endXP = (lvl + 1) ** 4
embed = discord.Embed(title = 'Level {}'.format(lvl), description = f"{exp} XP / {endXP} XP" ,color = discord.Color.green())
embed.set_author(name = ctx.author, icon_url = ctx.author.avatar_url)
await ctx.send(embed = embed)
else:
with open('level.json','r') as f:
users = json.load(f)
lvl = users[str(ctx.guild.id)][str(member.id)]['level']
exp = users[str(ctx.guild.id)][str(member.id)]['experience']
endXP = (lvl + 1) ** 4
embed = discord.Embed(title = 'Level {}'.format(lvl), description = f"{exp} XP / {endXP} XP" ,color = discord.Color.green())
embed.set_author(name = member, icon_url = member.avatar_url)
await ctx.send(embed = embed)
Another thing. Most of the people that comment on my posts nowadays comment about a certain question that has nothing to do with what I'm asking. If you want to bombard me with those comments, go do it in the question, not on this post. Thank you :)
#client.command()
async def leaderboard(ctx, x=10):
with open('level.json', 'r') as f:
users = json.load(f)
leaderboard = {}
total=[]
for user in list(users[str(ctx.guild.id)]):
name = int(user)
total_amt = users[str(ctx.guild.id)][str(user)]['experience']
leaderboard[total_amt] = name
total.append(total_amt)
total = sorted(total,reverse=True)
em = discord.Embed(
title = f'Top {x} highest leveled members in {ctx.guild.name}',
description = 'The highest leveled people in this server'
)
index = 1
for amt in total:
id_ = leaderboard[amt]
member = client.get_user(id_)
em.add_field(name = f'{index}: {member}', value = f'{amt}', inline=False)
if index == x:
break
else:
index += 1
await ctx.send(embed = em)
here is some code that may help

Categories

Resources