Bot is not waiting for the message - python

I'm trying to make the bot wait for a specific message(from a specific author and some specific things) But the bot is just waiting for any message and it makes the command.
Here's the function:
async def check(message):
if type == "netflix":
c.execute("SELECT price FROM netflix")
neprice = c.fetchall()
netprice= neprice[0][0]
netfprice = netprice*amount
nettax = await tax(args=netfprice)
try:
return message.mentions[0].id == 994347081294684240 and message.author.id == 282859044593598464 and int(nettax + netfprice) in message.content
except IndexError:
return False
Here's where I call the function:
await bot.wait_for('message', check=check, timeout=60)
Here's the full command:
#bot.slash_command()
#discord.ext.commands.cooldown(1,60, discord.ext.commands.BucketType.user)
async def buy(message, type: str, amount:Optional[int]):
if amount == None:
amount = 1
if amount < 0:
await message.respond("You cannot buy negative amount of accounts")
member = message.author
con = sqlite3.connect("db.sqlite")
c = con.cursor()
async def check(message):
if type == "netflix":
c.execute("SELECT price FROM netflix")
neprice = c.fetchall()
netprice= neprice[0][0]
netfprice = netprice*amount
nettax = await tax(args=netfprice)
try:
return message.mentions[0].id == 994347081294684240 and message.author.id == 282859044593598464 and int(nettax + netfprice) in message.content
except IndexError:
return False
elif type == "spotify" or "crunchyroll":
c.execute("SELECT price FROM spotify")
spotiprice = c.fetchall()
spotprice = spotiprice[0][0]
newspot = spotprice*amount
spotytax = await tax(args=newspot)
print(spotiprice[0][0])
try:
return message.mentions[0].id == 994347081294684240 and message.author.id == 282859044593598464 and int(newspot + spotytax) in message.content
except IndexError:
return False
if type == "netflix":
c.execute('SELECT *, COUNT(*) AS "count" FROM netflix GROUP BY price')
netamount= c.fetchall()
print(netamount[1])
if netamount[0][3] < amount:
await message.respond(f"We do not have this amount of accounts in the stock")
else:
c.execute("SELECT price FROM netflix ")
netfprice = c.fetchall()
netprice = netfprice[0][0]
newnet = netprice*amount
withtax = await tax(args=newnet)
embed = discord.Embed(title="transfer",description=f"Please transfer :{newnet + withtax}")
embed.add_field(name=f"c <#994347081294684240> {newnet + withtax}",value="**Copy paste the message for no error**")
embed.set_footer(text=f"Sidtho Host. | Requested by - {message.author}")
print("Sent embed, Waiting for receiving the credits")
await message.respond(embed=embed)
await bot.wait_for('message', check=check, timeout=60)
c.execute("SELECT email, password FROM netflix")
netres = c.fetchmany(size=amount)
# print(netres)
embed = discord.Embed(title=f"حساب {type}", description="")
embed.add_field(name="Sidtho Host.",value=" ",inline=False)
for thisamount in netres:
try:
email = thisamount[0]
password= thisamount[1]
embed.add_field(name=f"Email: {email}", value=f"Password: {password}", inline=False)
# print(f"The email is {email} \n The password is {password}
except TypeError as err:
print(f"Gave A TypeError. Where {err} ")
await member.send(embed=embed)
c.execute("DELETE FROM netflix WHERE email=? AND password=?",(email, password))
There is no traceback So no error.
Please note that the check function is a Function, not a command.
and the await bot.wait_for is on a command.
Please note too that type is a value that the user will give to the bot, and its not the python built.

In your code, you wrote await message.respond(...).
There isn't a respond() function in both discord.py and pycord, as far as I know. Try changing it to reply(...) and see if it works.

async def buy(message, type: str, amount:Optional[int]):
#type here the stuff that u want make before the check
def check(m):
return m.mentions[0].id == 994347081294684240 and m.author.id == 282859044593598464 and int(nettax + netfprice) in m.content
try:
response = await client.wait_for('message', check=check, timeout=30.0)
except:
#here u can send a message when the time is done
message.send("timeout")
return
so yeah it should look like this u take the response and run any checks on or save to db.

Related

Python error in telegram bot when editing a message

I see error:
(async_telebot.py:529 MainThread) ERROR - TeleBot: "59754269930"
In my code, I handle the callback:
select_item = {}
async def show_items(message, is_update):
with con.cursor() as cursor:
cursor.execute('SELECT * FROM items ORDER BY id ASC')
items = cursor.fetchall()
con.commit()
item = items[select_item[message.from_user.id]]
markup = types.InlineKeyboardMarkup(row_width=8)
btn1 = types.InlineKeyboardButton('one', callback_data='item1')
btn2 = types.InlineKeyboardButton('two', callback_data='item2')
markup.add(btn1, btn2)
msg = 'Test'
if is_update == False:
await bot.send_photo(chat_id=message.chat.id, photo=urllib.request.urlopen(item['image']), caption=msg, reply_markup=markup)
else:
await bot.edit_message_media(chat_id=message.chat.id, message_id=message.id, media=types.InputMedia(type='photo', media=open('start.jpg', 'rb')))
await bot.edit_message_caption(chat_id=message.chat.id, message_id=message.id, caption='edit')
#bot.message_handler()
async def get_user_text(message):
if message.text == 'Items':
if select_item.get('message.from_user.id') is None:
select_item[message.from_user.id] = 0
await show_items(message, False)
#bot.callback_query_handler(func=lambda call: True)
async def callback(call):
if call.message:
if call.data == 'item1':
await show_items(call.message, True)
And I don’t understand what the problem is, I’m a beginner, I need to process for each user the choice of the element that he will now scroll through
Checked data but it's ok
I found a solution:
if call.data == 'item1':
await show_items(call, True)
and
await bot.edit_message_media(chat_id=message.message.chat.id, message_id=message.message.id, media=types.InputMedia(type='photo', media=open('start.jpg', 'rb')))
await bot.edit_message_caption(chat_id=message.message.chat.id, message_id=message.message.id, caption='edit')
I mixed up the object, it referred to the message of the bot and not the user

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)

having problem with while loop not registering discord.py messages in condition

so what i'm trying to do is wait for a user's input which is !accept in discord so that my betting bot can do it's work as it's kinda dumb if a user can challenge another player and the other player can't deny the challenge so what i did is
while msg.content != "!accept" or msg.content != "!decline":
print("not yet given")
msg = await client.wait_for("message", check=lambda m: m.author.id == roller2 )
print("given")
note that i already have asked for msg from the other user/roller2 by doing
msg = await client.wait_for("message", check=lambda m: m.author.id == roller2 )
the reason why i know the while loop is the problem is the problem is because i found it by putting print statements in my code to see if a line works and it stops at the while loop specifically at msg = await client.wait_for("message", check=lambda m: m.author.id == roller2 )
i also printed the msg.content which was given by roller2 and even if it printed out !accept or !decline the code still wouldn't get past that part and i tried commenting out the while loop and the code worked so what i want to know is why it's not seeing !accept or !decline and how do i fix this
whole code:
#client.command()
#commands.cooldown(1, 30, commands.BucketType.user)
async def deathroll(ctx, user: discord.User, bet=100):
roller1 = ctx.author.id
roller2 = user.id
if roller1==roller2:
await ctx.send("you can't roll against yourself dumbass")
return
user2 = await client.fetch_user(roller2)
print(user2)
cursor.execute("SELECT id FROM DEATHROLL WHERE id = ?", (roller1,))
data = cursor.fetchall()
connect.commit()
print("1st")
if len(data) == 0:
await ctx.send("make an account first")
cursor.execute("SELECT id FROM DEATHROLL WHERE id = ?", (roller2,))
data = cursor.fetchall()
connect.commit()
print("2nd")
if len(data) == 0:
await ctx.send("please give a user for roller2")
msg = await client.wait_for("message", check=lambda m: m.author.id == roller2 )
cursor.execute("SELECT currency FROM DEATHROLL WHERE id=?", (roller1,))
roller1_cash = int(cursor.fetchone()[0])
connect.commit()
cursor.execute("SELECT currency FROM DEATHROLL WHERE id=?", (roller1,))
roller2_cash = int(cursor.fetchone()[0])
connect.commit()
print("3rd")
print(msg.content)#prints out !accept or !decline when roller2 sends !accept or !decline
while msg.content != "!accept" or msg.content != "!decline":
print("not yet given")
msg = await client.wait_for("message", check=lambda m: m.author.id == roller2 )
print("given")
if msg.content == "decline":
print("declined")
return
print("4th")#doesn't print out 4th due to while loop
cursor.execute("SELECT id FROM DEATHROLL WHERE id = ?", (roller2,))
data = cursor.fetchall()
print("5th")
if len(data) != 0:
roll = 100
while roll != 1:
roll = random.randint(1, roll)
await ctx.send("roller1,rolled:" + str(roll))
if roll == 1:
await ctx.send("the winner is roller1")
roller1_cash = roller1_cash - bet
roller2_cash = roller2_cash + bet
cursor.execute("UPDATE DEATHROLL set currency=? WHERE id=?", (roller1_cash, roller1))
connect.commit()
cursor.execute("UPDATE DEATHROLL set currency=? WHERE id=?", (roller1_cash, roller1))
connect.commit()
break
roll = random.randint(1, roll)
await ctx.send("roller2,rolled:" + str(roll))
if roll == 1:
await ctx.send("the winner is roller1")
roller1_cash = roller1_cash + bet
roller2_cash = roller2_cash - bet
cursor.execute("UPDATE DEATHROLL set currency=? WHERE id=?", (roller1_cash, roller1))
connect.commit()
cursor.execute("UPDATE DEATHROLL set currency=? WHERE id=?", (roller1_cash, roller1))
connect.commit()
break
There is a problem in the logic in your code in msg.content != "!accept" or msg.content != "!decline".
Let's say message content is "!decline", the program would check it like that:
"!decline" != "!accept" = True
"!decline" != "!decline" = False
Using or operator, returns True if one of the statements is True, so it returns True. So for this statement to be true, msg.content would have to be "!accept" and "!decline" at the same time. To fix this, simply use and instead of or.
Instead of the while loop, you could simply extend the check to include that the message content waited for has to be "!accept" or "!decline":
msg = await client.wait_for("message", check=lambda m: m.author.id == roller2 and m.content in ["!decline", "!accept"])
This could be used instead of the while loop.

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)

How can I make top 10 command work, where it grabs the top 10 in the JSON?

Here's my current code:
import discord
from discord.ext import commands
class Fun:
def __init__(self, client):
self.client = client
#commands.command(aliases=["lb"], pass_context=True)
async def leaderboard(self, ctx):
experience = self.getexperience()
with open('users.json') as f:
data = json.load(f)
lines = sorted(data.items(), key=operator.itemgetter(1), reverse=True) # sorts lines by balance
lb = [] # leaderboard
for line in lines: # each line in file
user = self.bot.get_user(id=int(line[0])) # grab user object from ID
if not user:
user = await self.bot.fetch_user(int(line[0]))
lb.append(f"{user.name} | {format(line[1], ',d')} {experience}\n") # add username and balance to leaderboard
limitedMsgs = [] # array for each page
pageCount = math.ceil(len(lb) / 10) # pageCount = number of users / 10 users per page
for x in range(0, pageCount): # for every page
limitedMsgs.append("".join(lb[x*10:x*10+10])) # add those 10 users to 1 page
currPage = 0
embed = discord.Embed(color=0xdfe324, description=limitedMsgs[0])
embed.set_footer(text=f"Page: {currPage + 1} of {pageCount}")
msg = await self.client.say(embed=embed)
def check(reaction, user):
return (user == ctx.message.author) and (str(reaction.emoji) == '⬅' or str(reaction.emoji) == '➡')
while(True):
if pageCount > 1:
if currPage == 0: # if first page
await msg.add_reaction("➡")
print(pageCount)
elif (currPage + 1) == pageCount: # if last page
await msg.add_reaction("⬅")
else: # if not first nor last
await msg.add_reaction("➡")
await msg.add_reaction("⬅")
try:
reaction, user = await self.bot.wait_for('reaction_add', timeout=60, check=check) # wait for user reaction
except asyncio.TimeoutError:
break # end while loop if no user reaction
if str(reaction.emoji) == '⬅':
currPage = currPage - 1
if str(reaction.emoji) == '➡':
currPage = currPage + 1
embed = discord.Embed(color=0xdfe324, description=limitedMsgs[currPage])
embed.set_footer(text=f"Page: {currPage + 1} of {pageCount}")
await msg.clear_reactions()
await msg.edit(embed=embed)
await msg.clear_reactions() # clear reactions after while loop
def setup(client):
client.add_cog(Fun(client))
heres the error:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Fun' object has no attribute 'getexperience'
Like I said before, I want it to grab the top 10 in the JSON, then order it into first to last but I'm stuck on this part. Most of this code is done; it's just the grabbing of the xp from the JSON. Any help would be appreciated. Thanks.
The error seems to be because of the line experience = self.getexperience(), as the full traceback should have pointed out. Your class/cog doesn't have the method, getexperience.

Categories

Resources