I can't solve the problem: I can't get the id of the user whose message I forwarded to the bot. When i forward a message i get my id. I'll be glad to help!!!!
My cod:
import telebot
bot = telebot.TeleBot('TOKEN')
#bot.message_handler(func=lambda message: True)
def send_welcome(message):
user_id = message.from_user.id
bot.send_message(message.chat.id, "ID: " + str(user_id))
if __name__ == '__main__':
bot.polling(none_stop=True)
Change message.from_user.id to message.forward_from.id
import telebot
bot = telebot.TeleBot('TOKEN')
#bot.message_handler(func=lambda message: True)
def send_welcome(message):
user_id = message.forward_from.id
bot.send_message(message.chat.id, "ID: " + str(user_id))
if __name__ == '__main__':
bot.polling(none_stop=True)
Related
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
For some reason my bot always turns off without printing any output to the command line or showing any kind of error. The bot functions properly for a few hours after being turned on. Basic code looks like this:
app = Client("my_account", '123456', '123456789abcd')
TESTING = "321"
USER_ID = "123"
chat_mapping = {TESTING: "-10011111111111", USER_ID: "-10011111111111"}
#app.on_message()
def my_handler(client, message):
if str(message.chat.id) not in chat_mapping:
return
elif str(message.chat.id) == USER_ID:
storeMsg(message)
else:
print(message.text)
app.run()
Any advice would be greatly appreciated!
if str(message.chat.id) not in chat_mapping
in this lane, your statement will check if message.chat.id is equal one of the keys of dictionary, not values.
Means your message.chat.id can't be 123 or 321.
USER_ID = some id
chat_mapping = [some ids]
#app.on_message()
def my_handler(client, message):
if str(message.chat.id) not in chat_mapping:
return
elif str(message.chat.id) == USER_ID:
storeMsg(message)
else:
print(message.text)
app.run()
I'm building a Telegram bot with the library https://github.com/eternnoir/pyTelegramBotAPI
I'm trying to make when I press a menu button, it sends a message to the user.
How could I do it?
import telebot
from telebot.types import InlineKeyboardMarkup, InlineKeyboardButton
TELEGRAM_TOKEN = '<TOKEN>'
bot = telebot.TeleBot(TELEGRAM_TOKEN)
def gen_markup():
markup = InlineKeyboardMarkup()
markup.row_width = 2
markup.add(InlineKeyboardButton("Yes", callback_data="cb_yes"),
InlineKeyboardButton("No", callback_data="cb_no"))
return markup
#bot.callback_query_handler(func=lambda call: True)
def callback_query(call):
if call.data == "cb_yes":
bot.answer_callback_query(call.id, "Answer is Yes")
elif call.data == "cb_no":
bot.answer_callback_query(call.id, "Answer is No")
#bot.message_handler(func=lambda message: True)
def message_handler(message):
bot.send_message(message.chat.id, "Yes/no?", reply_markup=gen_markup())
bot.polling(none_stop=True)
You can use data of your call object as the user id(call.from_user.id) of the sender to send a message:
if call.data == "cb_yes":
bot.answer_callback_query(call.id, "Answer is Yes")
bot.send_message(call.from_user.id,"Your answer was Yes!")
elif call.data == "cb_no":
bot.answer_callback_query(call.id, "Answer is No")
bot.send_message(call.from_user.id,"Your answer was No!")
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.