Line-Bot Python: writing users' answer into google sheet ERROR - python

#app.route("/callback", methods=['POST'])
def callback():
signature = request.headers['X-Line-Signature']
body = request.get_data(as_text=True)
app.logger.info("Request body: " + body)
try:
handler.handle(body, signature)
except InvalidSignatureError:
abort(400)
return 'ok'
def over_time(count):
scope = ["https://spreadsheets.google.com/feeds"]
creds = ServiceAccountCredentials.from_json_keyfile_name('auth.json', scope)
client = gspread.authorize(creds)
sheet = client.open('test').sheet1
content = sheet.cell(1,count).value
return content
#extract the questions from here
def write_in(answers):
scope = ["https://spreadsheets.google.com/feeds"]
creds = ServiceAccountCredentials.from_json_keyfile_name('auth.json', scope)
client = gspread.authorize(creds)
sheet = client.open('test').sheet1
sheet.insert_row(answers, 2)
# write users' answers into the sheet
users=[]
#handler.add(MessageEvent, message=TextMessage)
def handle_message(event):
global users
print("event.reply_token:", event.reply_token)
print("event.message.text:", event.message.text)
user_id = json.loads(str(event.source))['userId']
user_data ={}
location =0
count =0
answers =[]
for user in users:
if user_id==user['user_id']:
user_data =user
count =user_data['count']
location = [i for i, t in enumerate(users) if t['user_id'] == user_id][0]
answers = user_data['answers']
print(answers)
if user_data=={}:
user_data = {"user_id": user_id, "count": 0, "answers":[]}
users.append(user_data)
location=len(users)-1
if event.message.text == "a":
count=1
content = over_time(count)
users[location]['count'] = 1
line_bot_api.reply_message(
event.reply_token,
TextSendMessage(text=content))
return 0
if event.message.text == "b":
buttons_template = TemplateSendMessage(
alt_text='b template',
template=ButtonsTemplate(
title='type',
text='please choose',
thumbnail_image_url='xxxx',
actions=[
MessageTemplateAction(
label='a',
text='a'
),
]
)
)
line_bot_api.reply_message(event.reply_token, buttons_template)
return 0
if event.message.text != "a" and event.message.text != "b":
answers.append(event.message.text)
count += 1
if count>3:
b=write_in(answers)
print(b)
users[location]['count'] = 0
users[location]['answers'] = []
return 0 #
content = over_time(count)
users[location]['count'] = count
line_bot_api.reply_message(
event.reply_token,
TextSendMessage(text=content))
I actually know how to write them into google sheet. It's just when I tried to interact with users, sometimes it's acting weird. Everytime when a user finished answering the question, we will write its answer to the google sheet then set in blank again so the user can use it next time and fill a new answer. But I got error since some times line-bot would ask me Q1 twice or Q2 twice and didn't successfully write into google sheet. I think the error is mainly in the last part when count>3, I need to stop the whole process and not let it continue.
Steps when you use the line-bot:
write b -> press button a in the form -> Q1 -> A1 -> Q2 -> A2 -> Q3 -> A3 -> if count>3 -> answer=[A1,A2,A3] write into Google sheet -> Set the user data blank ->stop (then user can use it again)

Related

Python membership interface issues

I created member interface in Python. How can I connect this code to SQL server or do you have both SQL and Python code running dynamically?
ad = {'Ali':'Rıza'}
def kayit(gelen_ad,gelen_soyad):
ad[gelen_ad] = gelen_soyad
print((""""Adınız {} Soyadınız {} olarak kayıt oldunuz.
""").format(gelen_ad,gelen_soyad))
sor = input("Giriş yapmak istermisiniz? y/n >>>")
if sor=='y':
giris_kontrol(gelen_ad,gelen_soyad)
else:
exit()
def giris_kontrol(gelenad,gelensoyad):
s_d = False
for i in ad:
ad_g = i
soyad_g = ad[i]
if gelensoyad==soyad_g and gelenad==ad_g:
print(("""
Giriş başarılı oturum açıldı
Hoşgeldiniz {} {} Bey
""").format(ad_g,soyad_g))
s_d= True
if s_d==False:
print("""Hesap bulunamadı,Kayıt olmak istermisiniz?
y/n
""")
sor = input(">>>")
if sor == 'y':
ad_Sor = input("""
İsim:
""")
soyad_Sor = input("""
Soyad:
""")
kayit(ad_Sor,soyad_Sor)
else:
print("Çıkılıyor")
exit()
def kullanici():
ad = input('Adınız >>>')
soyad = input('Soyadınız >>>')
giris_kontrol(ad,soyad)
kullanici()
I created an interface to become a member and login. It did, but I can't provide SQL connection.

Calling Python Google Cloud Function via HTTP

I'm trying to call my Google Cloud Function via HTTP to get a response back in my browser. I expect a list of text, but am getting Error: could not handle the request.
Here's our code in the main.py source:
import openai
def gptinput(number,question,q_fc='q'):
#user_information = firebase.FirebaseReader()
openai.api_key = "___"
quest = "create '"+str(number)+ "' questions related to '"+question+"' with 4 options and print answer as ('ANSWER') and seperate each question with '/////'"
# Generate text using GPT-3
output_lis = []
while(len(output_lis)<number):
response = openai.Completion.create(
engine="text-davinci-002",
prompt= quest,
max_tokens=2048,
n=1,
stop=None,
temperature=0.5
)
# Extract the generated text
generated_text = response["choices"][0]["text"]
ans = generated_text.split("/////")
for i in ans:
q = i.split('?')
options= q[1][0:q[1].find("ANSWER")]
answer = q[1][q[1].find("ANSWER")+6:]
answer = answer.strip()
option_lis = options.split('\n')
option_lis.append(answer)
ques = q[0].strip()
option_lis = [s for s in option_lis if (s!='' or s!="")]
option_lis1 = [s for s in option_lis if (s!="\n" )]
output_lis.append({ques:option_lis1})
return output_lis[0:number]
`

I want help regarding tweepy hiding your username

So here is what I am trying to do I am trying to get my Twitter bot to give maths answers to users using WolframAlpha API
here is what problem I am facing
as people will mention my Twitter username to active the bot example: #twitterusername 2+2
the WolframAlpha will take it as the whole input #twitterusername 2+2 which will give me the error I want it to ignore the username
here is my code
def respondToTweet(file='tweet_ID.txt'):
last_id = get_last_tweet(file)
mentions = api.mentions_timeline(last_id, tweet_mode='extended')
if len(mentions) == 0:
return
new_id = 0
logger.info("someone mentioned me...")
for mention in reversed(mentions):
logger.info(str(mention.id) + '-' + mention.full_text)
new_id = mention.id
status = api.get_status(mention.id)
if '#Saketltd01' in mention.full_text.lower():
logger.info("Responding back with QOD to -{}".format(mention.id))
client = wolframalpha.Client(app_id)
query = mention.full_text.lower()
rest = client.query(query)
answer = next(rest.results).text
Wallpaper.get_wallpaper(answer)
media = api.media_upload("created_image.png")
logger.info("liking and replying to tweet")
api.create_favorite(mention.id)
api.update_status('#' + mention.user.screen_name, mention.id,
media_ids=[media.media_id])
put_last_tweet(file, new_id)
def main():
respondToTweet()
When you take the whole input remember to strip it down by simply removing your username from the actual input string and then perform the mathematical operation on it:
myUsername = "#my_username"
equation = userInput.lstrip(myUsername)
perform_desired_operation_on(equation) // User defined function

Python telegram bot, how to store and show users data for each users?

Hello I am new one for python and telegram api so i have some questions. I am creating telegram bot(python telegram api) with users profile. I have created database(mysql.connector) and store there all users info after registration. Also i have created user class. When user types /start i am checking if it exists, if it is, i am filling this class. Then i use this class to show some profile information(photo, name, age, etc.) if users click on button(my profile). So the problem is when i have 2-users at the same time. First typed "/start" and logged in, wanna watch self profile, everything fine. But when second user do the same, i got that the first users when clicked on (my profile), he or she got the last one profile who typed "/start" loaded for both users. How to fix this? Solution to check and load data all the time sounds not good, i'd like to do smth with "class Users", but i don't know to make it uniq for each users session. Any solutions? If it's needed i can give more code, just ask.
class Users:
def __init__(self, id=0, name='', age=0, gender='', balance=0, telegram_id=0, photo='', sallarytext=0, sallaryvideo=0, videocall=0):
self.id = id
self.name = name
self.age = age
self.gender = gender
self.balance = balance
self.telegram_id = telegram_id
self.photo = photo
self.sallarytext = sallarytext
self.sallaryvideo = sallaryvideo
self.videocall = videocall
user = Users()
def check_auth(connection, telegram_id):
cursor = connection.cursor()
result = None
try:
cursor.execute("SELECT * FROM users WHERE telegram_id = '%s'" % telegram_id)
result = cursor.fetchall()
data = []
if result:
for row in result:
user.id = row[0]
user.name = row[1]
user.age = row[2]
user.gender = row[3]
user.telegram_id = row[4]
user.balance = row[5]
data = [user.name]
if user.gender == 'Female':
cursor.execute("SELECT * FROM photos WHERE users_id = '%s'" % user.id)
result2 = cursor.fetchall()
for row in result2:
user.photo = row[1]
user.sallarytext = row[2]
user.sallaryvideo = row[3]
user.videocall = row[4]
return data
except Error as e:
print(f"The error '{e}' occurred")
#bot.message_handler(commands=['start'])
def check_reg(message):
if message.chat.type == 'private':
telegram_id = message.from_user.id
# create_db_users(connection)
# create_db_photos(connection)
# create_db_chats(connection)
data_user = check_auth(connection, telegram_id)
if not data_user:
new_user(message) # user registration
else:
if user.gender == 'Male':
default_user_keybord(message) # show user keybord
elif user.gender == 'Female':
default_model_keybord(message)
def show_profile(message): # funtion show profile when user click on "My profile" button
profile_text = "Profile\n\nYour name: " + user.name + "\nYour age: " + str(
user.age)
menu_keybord = types.ReplyKeyboardMarkup(row_width=2, resize_keyboard=True)
button_name_age = types.KeyboardButton(text="🗣 Change name/age")
button_back = types.KeyboardButton(text="◀️ Return")
menu_keybord.add(button_name_age, button_back)
bot.send_message(message.chat.id, profile_text, reply_markup=menu_keybord)
Could you tell me what telegram api package you are using exactly?
The core of your problem, I think, is the use of a global variable user to store user data. It would be best practice to instantiate and return a new Users every time you call check_auth.
That being said,
in Python, if you want to update a global variable, say user, you have to use the statement global user before you do so;
consider using an ORM such as SQLAlchemy to spare you some headaches and code.
Let me know if that solved your issue.
C
I have fixed this by doing request to the database, getting data and pushing it to class, then closing connection with database and showing to user

Google Clasroom Python API Use batch request and get the request back

I am new to google classroom api, just started a few days ago. I want to use batch request to make the code faster. My problem is that I don't know how to get the data back from the batch. I tried printing it in the console, but it returned null.
def get_all_courses(service):
nextpageToken = ""
list_id = []
while nextpageToken is not None:
result = service.courses().list(
pageSize=500,
pageToken=nextpageToken,
fields="nextPageToken,courses(id)"
)
result = result.execute()
lista_curs = result.get("courses")
for curs in lista_curs:
list_id.append(curs.get('id'))
nextpageToken = result.get("nextPageToken")
print("Ther are :" + str(len(list_id)))
return list_id
This is the normal usual code. How can I pass the request to a batch and get the results back?
batch1 = service.new_batch_http_request()
result = service.courses().list(
pageSize=500,
pageToken=nextpageToken,
fields="nextPageToken,courses(id)"
)
batch1.add(result)
batch1.execute()# how do I get back the result? do I have to call result.execute() again?
This is the code from the docs: https://developers.google.com/classroom/guides/batch
course_id = '123456'
student_emails = ['alice#example.edu', 'bob#example.edu']
def callback(request_id, response, exception):
if exception is not None:
print 'Error adding user "{0}" to the course course: {1}'.format(
request_id, exception)
else:
print 'User "{0}" added as a student to the course.'.format(
response.get('profile').get('name').get('fullName'))
batch = service.new_batch_http_request(callback=callback)
for student_email in student_emails:
student = {
'userId': student_email
}
request = service.courses().students().create(courseId=course_id,
body=student)
batch.add(request, request_id=student_email)
batch.execute(http=http) # what is http? what can I pass there? what kind of object is that?
Thank you in advance
Did you get a response from this? How have you handled the next page tokens and added them to the batch call?
def makeRequestWithExponentialBackoff(analytics):
for n in range(0, 5):
try:
response = service_two.courses().courseWork().studentSubmissions().list(pageToken=None, courseId=v['id'],
courseWorkId='-', pageSize=100000)
print(response.get("studentSubmissions", []))
return assignments.extend(response.get("nextPageToken", []))
except:
time.sleep((2 ** n) + random.random())
continue
print("There has been an error, the request never succeeded.")
def callback(request_id, response, exception):
if exception is not None:
print('Error getting assignments "{0}" for course: "{1}"'.format(request_id, exception))
makeRequestWithExponentialBackoff(request_id)
else:
assignments.extend(response.get("studentSubmissions", []))
nextPageToken = response.get("nextPageToken", None)
if nextPageToken:
iftoken(nextPageToken, request_id)
else:
pass
for k, v in filtered.iterrows():
if count % 1000 == 0:
submit = batch.execute(http=http)
batch_count += 1
print(batch_count)
time.sleep(30)
batch_array.append({'batchSent {}'.format(v['id'])})
batch = None
batch = service_two.new_batch_http_request(callback=callback)
response = service_two.courses().courseWork().studentSubmissions().list(pageToken=None, courseId=v['id'],
courseWorkId='-', pageSize=100000)
batch.add(response, request_id=v['id'])
array.append({'email': v['primaryEmail'], 'count': count, 'classid': v['id']})
count = 1
elif count % 1000 != 0 and batch == None:
batch = service_two.new_batch_http_request(callback=callback)
response = service_two.courses().courseWork().studentSubmissions().list(pageToken=None, courseId=v['id'],
courseWorkId='-', pageSize=100000)
batch.add(response, request_id=v['id'])
array.append({'email': v['primaryEmail'], 'count': count, 'classid': v['id']})
count += 1
else:
response = service_two.courses().courseWork().studentSubmissions().list(pageToken=None, courseId=v['id'],
courseWorkId='-', pageSize=100000)
batch.add(response, request_id=v['id'])
array.append({'email': v['primaryEmail'], 'count': count, 'classid': v['id']})
count += 1
where filtered is a dataframe of classroom Ids. However got an issue with the nextpagetokens and how to add these to the dataframe?

Categories