Hello everyone! I need an advice for better understanding of Python's structure and syntax. No idea what's goin on.
Here is my code:
import telebot
import random
import time
from telebot import types
bot = telebot.TeleBot('token_name')
#bot.message_handler(commands=['start'])
def website(message):
markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=3)
war = types.KeyboardButton('A')
star = types.KeyboardButton('B')
markup.add(war, star)
bot.send_message(message.chat.id, 'CHOOSE:', reply_markup=markup)
#bot.message_handler(content_types=['text'])
def func(message):
if (message.text == "A"):
markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
btn1 = types.KeyboardButton("1")
btn2 = types.KeyboardButton("2")
btn3 = types.KeyboardButton("3")
markup.add(btn1, btn2, btn3)
bot.send_message(message.chat.id, text="CHOOSE YOUR:", reply_markup=markup)
Everything is ok before this part:
elif (message.text == "B"):
markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=3)
war = types.KeyboardButton('THIS')
star = types.KeyboardButton('THIS THIS')
markup.add(war, star)
bot.send_message(message.chat.id, 'CHOOSE:', reply_markup=markup)
#bot.message_handler(commands=['THIS THIS'])
def website (message):
markup = types.InlineKeyboardMarkup()
markup.add(types.InlineKeyboardButton("1"))
bot.send_message(message.chat.id, 'CODE OF YOUR ORDER: №' + str(random.randint(10000, 99999)) +'<b>PAY</b>',parse_mode="html", reply_markup=markup
)
bot.polling(none_stop=True)
I expected result with Inline.Keyboard in message (example in picture №3). And also random number. In PyCharm i have clear terminal (no warnings, no errors). And Telegram without reply. No idea how i can fix this. I need button '1' inside message and random number. I think there is a conflict, because code already has [text] early, but still i can't fix this.
enter image description here
enter image description here
enter image description here
Related
I want to write a code that continues the message box after receiving an answer.
for example: If they answer yes they get another message box, and same applies for no.
I'm not sure how to word it correctly i hope it makes sense.
I've tried with this:
import tkinter
import tkinter.messagebox
tkinter.messagebox.askyesno(title = "Reginának" , message = "Mizu?")
answer = (tkinter.messagebox.askyesno = "yes")
if answer != "yes"
tkinter.messagebox.showwarning(title = "Reginának" , message = "Persze")
Although i do know that it's not right i was just trying to do something with my limited knowledge :))
Try this.
Code:
from tkinter import *
from tkinter import messagebox
ws = Tk()
ws.title('Python Guides')
ws.geometry('300x200')
ws.config(bg='#5FB691')
res = messagebox.askquestion('Reginának', '"Mizu?')
if res == 'yes':
messagebox.showinfo('Reginának', 'Persze')
elif res == 'no':
messagebox.showinfo('Reginának', 'You must be a Pele\'s fan.')
else:
messagebox.showwarning('error', 'Something went wrong!')
ws.mainloop()
I'm trying to get code from user and if it's correct to start sending him options.
But the third function (send_welcome) doesn't start. Could you say what I'm missing?
#bot.message_handler(commands=['start'])
def send_text_request(message):
msg = bot.send_message(message.chat.id, "Write a code")
bot.register_next_step_handler(msg, function)
def function(message):
if message.text=='6':
print('hello')
bot.register_next_step_handler(message, send_welcome)
def send_welcome(message):
markup=types.ReplyKeyboardRemove(selective=False)
markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=2)
itembtn1 = types.KeyboardButton("option1")
itembtn2 = types.KeyboardButton("option2")
markup.add(itembtn1, itembtn2)
msg = bot.send_message(message.chat.id, "Hello "+message.from_user.first_name+", I will help you! \n Enter the product", reply_markup=markup)
I'm trying to make /stop command for the bot (the greetings stop to send). It works, but only one time, after pressing the /start command it is unable to stop again and runs forever.
Tried different methods of stopping, manged either to stop and unable to restart or to stop once and unable to stop after repeating /start or "greet".
I would be very grateful for the advice of how to improve the existing code
import random, telebot, schedule, time
from telebot import types
from config import token
bot = telebot.TeleBot(token)
greetings = ["hello", "Have a nice day", "Goodbye", "Wow"]
#bot.message_handler(commands=['start'])
def start_message(message):
markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
item1 = types.KeyboardButton("Greet")
markup.add(item1)
bot.send_message(message.chat.id, "Press button", reply_markup=markup)
#bot.message_handler(content_types=["text"])
def run_function(message):
def function_to_run():
random_greet = random.choice(greetings)
bot.send_message(message.chat.id, random_greet)
def scheduling():
schedule.every(4).seconds.do(function_to_run).tag('schedule')
scheduling()
if message.text.lower() == "greet":
bot.send_message(message.chat.id, "here you go")
function_to_run()
def schedule_run():
while True:
schedule.run_pending()
time.sleep(1)
schedule_run()
elif message.text.lower() == "stop":
bot.send_message(message.chat.id, "stopping...")
schedule.clear('schedule')
time.sleep(1)
bot.send_message(message.chat.id, "stopped successfully")
bot.polling()
import random, telebot, schedule, time
from telebot import types
from config import token
bot = telebot.TeleBot(token)
greetings = ["hello", "Have a nice day", "Goodbye", "Wow"]
#bot.message_handler(commands=['start', 'stop'])
def start_message(message):
command = message.text.split()[0]
if command == "/start":
markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
item1 = types.KeyboardButton("Greet")
markup.add(item1)
bot.send_message(message.chat.id, "Press button", reply_markup=markup)
elif command == "/stop":
bot.send_message(message.chat.id, "stopping...")
schedule.clear('schedule')
time.sleep(1)
bot.send_message(message.chat.id, "stopped successfully")
exit()
#bot.message_handler(content_types=["text"])
def run_function(message):
...
# or
elif message.text.lower() == "stop":
bot.send_message(message.chat.id, "stopping...")
schedule.clear('schedule')
time.sleep(1)
bot.send_message(message.chat.id, "stopped successfully")
exit()
bot.polling()
if you want to on it again try this:
import random, telebot, schedule, time
from telebot import types
from config import token
bot = telebot.TeleBot(token)
greetings = ["hello", "Have a nice day", "Goodbye", "Wow"]
on = True
#bot.message_handler(commands=['start', 'stop'])
def start_message(message):
global on
command = message.text.split()[0]
if command == "/start" and not on:
on = True
# your code
if command == "/stop" and on:
on = False
# your code
#bot.message_handler(content_types=["text"])
def run_function(message):
global on
if on:
# your code
bot.polling()
I'm new in development and python too. I tried to write a simple telegram bot using Telebot. The scenario is to show inline keyboard to user when user click on button do some logic. In Example below I cut the code but it showing the problem. And the problem is:
When first user start working he gets correct and all notifications. But when second user starts to work with bot he gets correct keyboard but notification will send to First user.
Here is a code example:
import telebot
import datetime
bot = telebot.TeleBot(insert_token_here)
keyboard1 = telebot.types.ReplyKeyboardMarkup(True)
keyboard1.row('Choose date', 'dont push it')
#bot.message_handler(commands=['start'])
def start_message(message):
bot.send_message(message.chat.id, 'Welcome', reply_markup=keyboard1)
def dates_inline():
current_date = datetime.datetime.today()
# Inline keyboard
keyboard_dates = telebot.types.InlineKeyboardMarkup()
key_now = telebot.types.InlineKeyboardButton(text=current_date.strftime('%d.%m.%Y') + ' (Today)',
callback_data=current_date.strftime('%Y-%m-%d'))
keyboard_dates.add(key_now)
return keyboard_dates
#bot.message_handler(content_types=['text'])
def choose_message(message):
if message.text == "Choose date":
bot.send_message(message.chat.id, 'Choose date:', reply_markup=dates_inline())
#bot.callback_query_handler(func=lambda call: True)
def choose_date(call):
dt = call.data
print('chose_date dt: %s' % dt)
bot.send_message(message.chat.id, 'All done')
print('end')
else:
print('smth else')
def main():
bot.polling(none_stop=True)
if __name__ == '__main__':
main()
I also faced a similar problem.
Do not create a handler/decorator inside another one. It doesn't work like that. I'm also relatively new to python, so I don't know the exact reason. I also learned it from my mistake.
Do not send messages back to message.chat.id . send it to call.from_user.id so that it'll always send the reply back to the user from whom the call came.
#bot.message_handler(content_types=['text'])
def choose_message(message):
if message.text == "Choose date":
bot.send_message(message.chat.id, 'Choose date:', reply_markup=dates_inline())
else:
print('smth else')
#bot.callback_query_handler(func=lambda call: True)
def choose_date(call):
dt = call.data
print('chose_date dt: %s' % dt)
bot.send_message(call.from_user.id, 'All done')
print('end')
I am also in the development of a bot right now and this is working fine for me.
You need to move following code to top-level indentation. Otherwise it works not as you intended.
#bot.callback_query_handler(func=lambda call: True)
def choose_date(call):
dt = call.data
print('chose_date dt: %s' % dt)
bot.send_message(message.chat.id, 'All done')
#wowkin2 Here is a sample code:
#bot.message_handler(content_types=['text'])
def choose_message(message):
if message.text == "Choose date":
bot.send_message(message.chat.id, 'Choose date:', reply_markup=dates_inline())
print('end')
else:
print('smth else')
#bot.callback_query_handler(func=lambda call: True)
def choose_date(call):
dt = call.data
bot.send_message(message.chat.id, 'All done')
I have a question about building a telegram bot with python.
How can I get input from the user in my python-telegram-bot?
For example, a dictionary bot, how can I get a word from the user?
I recommend to have a look at the examples on GitHub.
With python-telegram-bot v12.0.0b1 you can do it like this:
def do_something(user_input):
answer = "You have wrote me " + user_input
return answer
def reply(update, context):
user_input = update.message.text
update.message.reply_text(do_something(user_input))
def main():
updater = Updater("TOKEN", use_context=True)
dp = updater.dispatcher
dp.add_handler(MessageHandler(Filters.text, reply))
updater.start_polling()
updater.idle()
I recommend pyTelegramBotAPI, not python-telegram-bot.
For me it is easier.
And you should use this:
#bot.message_handler(func=lambda message: True)
def echo_message(message):
cid = message.chat.id
mid = message.message_id
message_text = message.text
user_id = message.from_user.id
user_name = message.from_user.first_name
You can save this information in JSON if you want.