Inline mode Telegram bot, problem with the request - python-3.x

I am writing a telegram bot with inline mode, everything is fine, but I am faced with such a situation. When I wrote this code:
text = inline_query.query or '0'
the problem is that when I enter data in the chat, it returns to me, first 0, then symbolically and then the total integer value that I entered.
Is it possible to get rid of this so that it outputs the current that I sent in the chat ?
I tried to prescribe a condition but it didn't work out.
For example, I entered 123 and if I write somewhere or just output it, it turns out 0 , 1, 12 ,123.
I want to get the value without unnecessary garbage and so that I can continue to work with it. if something is not clear, I will supplement it
My code:
#dp.inline_handler()
async def inline_money(inline_query: types.InlineQuery) -> None:
text = inline_query.query or '0'
result_id = str(uuid.uuid4().hex)
input_content = InputTextMessageContent(text_all_1)
keyboard = InlineKeyboardMarkup()
button = InlineKeyboardButton('Payment page')
item_2 = InlineQueryResultArticle(
input_message_content=input_content,
id=str(uuid.uuid4().hex),
title='Page',
reply_markup=keyboard.add(button)
)
if text != "0":
cur = conn.cursor()
text_new = float(text)
cur.execute("INSERT INTO payments (indexer, price) VALUES (%s, %s)", (result_id, text_new))
conn.commit()
else:
pass
await bot.answer_inline_query(inline_query_id=inline_query.id, results=[item_2], cache_time=1)

Related

passing one function to another inside a for loop

New to programming. I wrote a program that Asks the user to enter the name, age and shoe size for four people and adds it to a dictionary. In fact, it works even when I don't use one function as an argument for another function. However, when i try to pass get_user_info() to store_user_info it doesnt work. I also tried to pass get_user_info to three separate variables and then passed these variables to store_user_info and it still didn't work. I am probably making a dumb error. Sorry its kind of a basic type of query but I just started learning programming. Any guidance is appreciated.
FOLLOWING CODE DOESN'T WORK: IT RUNS THE FOR LOOP BUT NEVER PROMPTS FOR THE INPUT FOR MORE THAN ONCE
#get user info
def get_user_info():
while True:
try:
user_input_name = (input("What is your name "))
user_input_age = int(input("How old are you "))
user_input_shoesize = float(input("What is your show size "))
break
except (ValueError,IndexError):
print('wrong selection or input')
return user_input_name,user_input_age,user_input_shoesize
#Store user info
def store_user_info(user_info):
user_information = {}
for i in range(3):
name, age, shoesize = user_info
user_information[name] = {"age" : age,"shoesize": shoesize}
print(user_information)
return user_information
=
store_user_info(get_user_info())
YET THE FOLLOWING WORKS and the loop works 3 times as expected:
#get user info
def get_user_info():
while True:
try:
user_input_name = (input("What is your name "))
user_input_age = int(input("How old are you "))
user_input_shoesize = float(input("What is your show size "))
break
except (ValueError,IndexError):
print('wrong selection or input')
return user_input_name,user_input_age,user_input_shoesize
#Store user info
def store_user_info():
user_information = {}
for i in range(3):
name, age, shoesize = get_user_info()
user_information[name] = {"age" : age,"shoesize": shoesize}
print(user_information)
return user_information
store_user_info()

regex doesn't seem to work in allowRegexes parameter when using pyinputplus

I am using pyinputplus and specifically inputNum
https://pyinputplus.readthedocs.io/en/latest/
This is what my code looks like:
msg = 'Enter value to add/replace or s to skip field or q to quit: '
answer = pyip.inputNum(prompt=msg, allowRegexes=r'^[qQsS]$', blank=False)
My goal is to allow any number but also allow one of the following q,Q,s,S.
However when I run the code and enter 'sam' the code crashes because later on I am trying to convert to float(answer).
My expectation is that allowRegexes will not allow this and will show me the prompt again to re-enter.
Please advise!
It seems pyip.inputNum stops validating the input if you provide allowRegexes argument. See the allowRegexes doesn't seem work properly Github issue.
You can use the inputCustom method with a custom validation method:
import pyinputplus as pyip
import ast
def is_numeric(x):
try:
number = ast.literal_eval(x)
except:
return False
return isinstance(number, float) or isinstance(number, int)
def raiseIfInvalid(text):
if not is_numeric(text) and not text.casefold() in ['s', 'q']:
raise Exception('Input must be numeric or "q"/"s".')
msg = 'Enter value to add/replace or s to skip field or q to quit: '
answer = pyip.inputCustom(raiseIfInvalid, prompt=msg)
So, if the text is not and int or float and not equal to s/S/q/Q, the prompt will repeat showing up.

How can I use something stored in a DataBase? SQLite / Python

So, I am new at DataBases and I have a question. I first made a re-search in the internet but could not find anything or actually I could not understand correctly what they were explaining. Before starting with my question I want to say that I am currently working in a Discord Bot in Python as Main Language and I am trying to create a per-server-prefix system. I have already made it once but in .JSON format. Then I heard that using .JSON to save this kind of Data is not actually good so I moved to DataBases. Now, my question is:
I have stored the guild_id and prefix in my DB, how could I use that for a per-server-prefix system? I have not tried anything yet except writing the Code to store both Texts. I would really love if anyone could explain to me not just tell me the Code! Any answer will be appreciated <3.
Main.py:
def get_prefix(client, message):
db = sqlite3.connect("main.sqlite")
cursor = db.cursor()
cursor.execute(f"SELECT prefix FROM prefixes WHERE guild_id = {message.guild.id}")
result = cursor.fetchone()
if result is None:
return "/"
else:
client = commands.Bot(command_prefix = get_prefix)
Prefixes.py (COGS):
#commands.command()
#commands.has_permissions(administrator=True)
async def prefix(self, ctx, prefix=None):
db = sqlite3.connect("main.sqlite")
cursor = db.cursor()
cursor.execute(f"SELECT prefix FROM prefixes WHERE guild_id = ?", ctx.guild.id)
result = cursor.fetchone()
if result is None:
sql = ("INSERT INTO prefixes(guild_id, prefix) VALUES(?,?)")
val = (ctx.guild.id, prefix)
await ctx.channel.send(f"{prefix}")
elif result is not None:
sql = ("UPDATE prefixes SET prefix = ? WHERE guild_id = ?")
val = (prefix, ctx.guild.id)
await ctx.channel.send(f"update `{prefix}`")
cursor.execute(sql, val)
db.commit()
cursor.close()
db.close()
That is pretty much the whole code. If you think anything should be changed or have any suggestions, answer in the comments!
All you need to do is, after the else, put return result. For example:
result = cursor.fetchone()
if result is None:
return "/"
else:
return result
cursor.fetchone() returns a tuple with each element requested in the row, as you only requested the prefix, it will contain just that (e.g: ("!",)) which is permitted as your command_prefix callable can return a string or tuple of strings.
Warning:
You may want to add a check to ensure that someone doesn't specify an empty string (A zero length string with nothing in it) as their prefix, otherwise your bot will attempt to run every message it sees as a command
References: discord.ext.commands.Bot.command_prefix

Accessing a database of ID numbers to validate against an entered number Python3

I'm trying to get the user to enter in a pin number (four numbers) which the database will then validate by looking at the customer ID's. At the moment, it works if I get the user to enter any of the ID pins and I program it so they can enter any ID for them to access, but I want them to access their own accounts. So if I enter, for example, Jeremy's unique pin, it will prompt me with a hello Jeremy message. At the moment, if I enter a four digit number, nothing simply happens. The code I have so far is :
def entryID():
print("Hello")
print()
print()
print("Welcome to the Northern Frock ATM system")
time.sleep(2)
print("In order for you to access the machine, you must enter a correct PIN")
with sqlite3.connect("ATM.db") as db:
cursor = db.cursor()
cursor.execute("select CustomerID from ATM")
userIDs = cursor.fetchall()
print(userIDs)
UserID = input("Please enter your Customer ID. If you want to quit, type in 99999\n")
if UserID == userIDs[0]:
print('Hello smack')
elif UserID == userIDs[1]:
print("Hello joe")
elif UserID == userIDs[2]:
print("Hellow Snow")
elif UserID == userIDs[3]:
print("Hellow Moe")
fetchall() returns a list of rows. Each row is a list of column values.
So userIDs[0] is the first row, i.e., something like (1234,).
To access the actual value, you have to extract the first column from the row:
if UserID == userIDs[0][0]:
...
Please note that a query can return results in a random order unless you are using ORDER BY.
And it might be a better idea to store the customer names in the database, and load only the one you want:
cursor.execute('SELECT Name FROM ATM WHERE CustomerID = ?', [UserID])
for (name,) in cursor:
print("Hello " + name)
else:
print("wrong!")

Trouble with IF statement Python

I'm having trouble with an IF statement resulting from when a button is clicked.
The code I have so far is below, basically what I need is once the button is pressed it asks the question 'Are you sure you want to update?' This works fine. The user then clicks yes or no. No closes the pop up box (working ok), if the user clicks yes then it checks to see if the entry is blank. If it is it keeps the original variable (working ok), it also checks to see if the entry is a float and if it isn't then return an error message, this brings back an error message even if it is a float, what I want it to do is if its a float then use the entered value which the else statement should do. but it keeps bringing back the messagebox error.
def updatetimings():
ask = messagebox.askquestion('Validation','Are you sure you want to update timings?')
if ask =='yes':
try:
a = newv5c.get()
if a == "":
e1 = v5c_timing
elif type(a) != float :
messagebox.showinfo('Error','Please enter decimal numbers only')
else:
e1 = a
except ValueError:
messagebox.showinfo('Error','Please enter decimal numbers only')
pass
Maybe Psuedocode may help:
BUTTON CLICKED:
QUESTION ASKED
NO CLOSES WINDOW
YES = IF ENTRY IS BLANK THEN USE OLD VARIABLE
OR ENTRY = FLOAT THEN USE NEW VARIABLE
IF ITS ANY OTHER TYPE THEN SHOW ERROR MESSAGEBOX ,'WRONG TYPE'
I've set the entry as a StringVar() if that is the problem.
Thanks
In their comment, hiro protagonist suggested that a might always be a str. I agree that this is probably the case (although I don't know for sure). This is one way to structure your code to use float() to parse a value out of a:
def updatetimings():
ask = messagebox.askquestion('Validation','Are you sure you want to update timings?')
if ask == 'yes':
a = newv5c.get()
if a == '':
e1 = v5c_timing
else:
try:
# Try parsing a as a float. If it works, store the result in e1.
e1 = float(a)
except ValueError:
# If we're not able to parse a as a float, then show an error message.
messagebox.showinfo('Error','Please enter decimal numbers only')
I hope this helps!

Resources