I'm trying create a news telegram bot. But iI can't send messages with interactive buttons.
The reason why I use the buttons is to make a menu, I would appreciate if you could show an example of making an interactive menu instead of just adding it.
Using Language : Python 3.9 & Telebot Library
Like this:
Telebot provides the following types for InlineKeyboard:
InlineKeyboardMarkup; The keyboard
InlineKeyboardButton; The markup button
An basic example would look like
from telebot import TeleBot
from telebot import types
bot = TeleBot("859163076:A......")
chat_id = 12345
button_foo = types.InlineKeyboardButton('Foo', callback_data='foo')
button_bar = types.InlineKeyboardButton('Bar', callback_data='bar')
keyboard = types.InlineKeyboardMarkup()
keyboard.add(button_foo)
keyboard.add(button_bar)
bot.send_message(chat_id, text='Keyboard example', reply_markup=keyboard)
Which will result in the following message send to chat_id:
use callback query handler, there is example here:
https://github.com/eternnoir/pyTelegramBotAPI/blob/master/examples/inline_keyboard_example.py
Related
I want to create an object when the user press /start in a Telegram bot, and then share this object among all the commands of the bot. Is this possible? As far as I understand, there's only one thread of your bot running in your server. However, I see that there is a context in the command functions. Can I pass this object as a kind of context? For example:
'''
This is a class object that I created to store data from the user and configure the texts I'll display depending on
the user language but maybe I fill it also with info about something it will buy in the bot
'''
import configuration
from telegram import Update, ForceReply
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackContext
# Commands of the bot
def start(update: Update, context: CallbackContext) -> None:
"""Send a message when the command /start is issued."""
s = configuration.conf(update) #Create the object I'm saying
update.message.reply_markdown_v2(s.text[s.lang_active],
reply_markup=ForceReply(selective=True),
)
def check(update: Update, context: CallbackContext) -> None:
"""Send a message when the command /start is issued."""
s = configuration.conf(update) # I want to avoid this!
update.message.reply_markdown_v2(s.text[s.lang_active],
reply_markup=ForceReply(selective=True),
)
... REST OF THE BOT
python-telegram-bot already comes with a built-in mechanism for storing data. You can do something like
try:
s = context.user_data['config']
except KeyError:
s = configuration.confi(update)
context.user_data['config'] = s
This doesn't have to be repeated in every callback - you can e.g.
use a TypeHandler in a low group to create the config if needed. then in all handlers in higher groups, you don't need to worry about it
use a custom implementation of CallbackContext that adds a property context.user_config
Disclaimer: I'm currently the maintainer of python-telegram-bot.
I need my telegram bot to forward messages from the private chat to the customer care staff group.
I run this code:
#bot.message_handler(func=lambda message: message.chat.type=='private')
def forwarder(message):
bot.forward_message(group, message.chat.id, message.id)
bot.send_message(group, '#id'+str(message.chat.id))
It works smoothly with text messages, but does nothing with photos.
Even if I remove all previous message handlers, so there is no conflict with them to handle photos, it still keeps doing nothing.
If I use the get.updates() method I can check "manually" if the photo has arrived and I find it.
Edit: Even if i just run this code only
import telebot
bot = telebot.TeleBot("MY TOKEN")
#bot.message_handler(func=lambda message: True)
def trivial(message):
print('yes')
bot.polling()
I get 'yes' for text messages and absolutely nothing, not even raised exceptions for photos.
If you add content_types as a parameter you will receive whatever is specified in the argument (which takes an array of strings). Probably the default value for that parameter is set to ['text']. Which will only listen for 'text' messages.
To get the results you're looking for
your test code will look like:
import telebot
bot = telebot.TeleBot("MY TOKEN")
#bot.message_handler(func=lambda, message: True, content_types=['photo','text'])
def trivial(message):
print('yes')
bot.polling()
And your working code:
#bot.message_handler(func=lambda, message: message.chat.type=='private', content_types=['photo','text'])
def forwarder(message):
bot.forward_message(group, message.chat.id, message.id)
bot.send_message(group, '#id'+str(message.chat.id))
In Telegram Bot API there is a resource /sendphoto
See:
Sending message in telegram bot with images
Try to find the related method in the PyTelegramBotApi.
Or implement the function to send a photo your own (e.g. using requests library in Python). Then you can use it in the message-handlers of your bot, to forward images.
Some weird thing with telegram api. I am trying to send audio from telegram bot and by the way to change performer and title, but I can't. First of all I thoght I made a mistake, but not! I tried to do the same thing from the browser search line becouse there is no chance to do something wrong, and no results! May be you can try to do the same thing? It would be great, becouse I don't know what is wrong. I am trying to do it on Python with pyTelegramBotAPI. For example code:
import telebot
import const
#Подключаюсь к боту
bot = telebot.TeleBot(const.token)
#bot.message_handler(content_types=["text"])
def handle_command(message):
a = bot.send_audio(message.from_user.id, musicurl, caption=None, duration=None, performer="Pharik", title="hfdhdfh",
reply_to_message_id=None)
print(a.audio.performer)
print(a.audio.title)
bot.polling(none_stop=True, interval=0)
I discover that you can't set performer and title parameters if you upload audio file by the link. If you are doing it with local file, it works. There is one way I see, take the file from link, download it, use EasyId3 to rewrite meta of mp3 file and after that send it to Telegram. But it's weird I think. Maybe it's a mistake, becouse Telegram Bot API has this parameters and it doesn't work. However Telegram uploads files on own servers, so they can change meta on their side using parametrs. Where is the logic? How knows any solutions?
I used Mp3tag to edit Title (title) and Artist (performer) of the mp3 file and Telegram use it to display after uploaded.
I am creating a telegram bot and using sendMessage method to send the messages.
it is easy to mention user using #username, But how to mention user when they don't have username?
If using the telegram app/web, we can mentioned the user by #integer_id (name), and telegram app/web will convert it into clickable text. integer_id will be generated automatically when we select the user, after typing #.
another background:
I am trying to use forceReply and I want to target user, if they have username, I can easily target them, by mentioning them on the text on sendMessage method.
the bot I am creating is a "quiz" like bot. where each player need to take turn, and the bot is sending them the question, each msg from bot will target different player.
NOTE: I am not disabling the Privacy Mode, I don't want telegram bombing my server with msg I don't need. it was overloading my cheap nasty server. so, disabling it not an option.
I am open for other solution, where the bot can listen to selected player.
thanks.
UPDATE 21/10:
I've spoke to BotSupport for telegram, they said, for now Bots can't mention user without username.
so in my case, I still keep using forceReply, and also, gave a short msg to user which doesn't have username to set it up, so they can get the benefit from forceReply function.
According to official documentation it is possible to mention user by its numerical id with markup:
[inline mention of a user](tg://user?id=123456789)
According to this link :
it is possible to mention user by its numerical id with markup:
Markdown style
To use this mode, pass Markdown in the parse_mode field
when using sendMessage. Use the following syntax in your message:
[inline mention of a user](tg://user?id=123456789)
and you can also use HTML style :
HTML style
To use this mode, pass HTML in the parse_mode field when using sendMessage. The following tags are currently supported:
inline mention of a user
Try this:
#bot.message_handler(func=lambda message: True)
def echo_message(message):
cid = message.chat.id
message_text = message.text
user_id = message.from_user.id
user_name = message.from_user.first_name
mention = "["+user_name+"](tg://user?id="+str(user_id)+")"
bot_msg = f"Hi, {mention}"
if message_text.lower() == "hi":
bot.send_message(cid, bot_msg, parse_mode="Markdown")
For python-telegram-bot you can do the following:
user_id = update.message.from_user['id']
user_name = update.message.from_user['username']
mention = "["+user_name+"](tg://user?id="+str(user_id)+")"
response = f"Hi, {mention}"
context.bot.sendMessage(chat_id=update.message.chat_id,text=response,parse_mode="Markdown")
No, this restriction is related to Telegram's privacy policy and prevention of abuse.
It is possible to mention a user when sending messages (BOT API), but that is not what you need:
[inline mention of a user](tg://user?id=<user_id>)
Links tg://user?id= can be used to mention a user by their id without using a username. Please note:
These links will work only if they are used inside an inline link. For example, they will not work, when used in an inline keyboard button or in a message text.
These mentions are only guaranteed to work if the user has contacted the bot in the past, has sent a callback query to the bot via inline button or is a member in the group where he was mentioned.
https://core.telegram.org/bots/api#markdown-style
you need to link to the text: "tg://user?id=" and id
user_id = 123456XX # id of the user to mention
chat_id = 123456XXX # chat id where to mention
user_name = name of user
await bot.send_message(chat_id, f"<a href='tg://user?id={user_id}'>{user_name}</a>", "HTML")
here is an example:
#dp.message_handler()
async def mention(msg: types.Message):
await msg.answer(f"<a href='tg://user?id={msg.from_user.id}'>{msg.from_user.full_name}</a>", "HTML")
Bots are able to tag users by their ID, they just can't do this using the official HTTP Bot API.
Update: Not necessairy anymore, since Telegram added native Support for this.
If you log into your bots account with MadelineProto (PHP) you can use this 'link' to mention someone by it's ID with parse_mode set to markdown
[Daniil Gentili](mention:#danogentili)
i wanted to enter some text to a text field in my android application.I installed the app and in the second page i wanted to search for some places.For that i need to enter some text.
I tried `device.press('KEYCODE_BUTTON_SELECT',MonkeyDevice.DOWN_AND_UP)
device.press('KEYCODE_i','DOWN_AND_UP')
device.press('KEYCODE_n','DOWN_AND_UP')
device.press('KEYCODE_d','DOWN_AND_UP')
device.press('KEYCODE_i','DOWN_AND_UP')
device.press('KEYCODE_a','DOWN_AND_UP')
or
Device.type(India)`
But these commands are not working for my application.,It is not entering string "India" to my application text filed.But this is working with phone native search text filed.
I installed Android View Client and import the following things
import from com.dtmilano.android.view client import View Client
from com.android.monkey runner import Monkey Runner, Monkey Device
Then i wrote the code like this
vc = ViewClient(device)
vc.dump()
address= vc.findViewById('search')
address.type('india')
But it is showing error: 'None Type' object has no attribute 'type'.
Can u pls help me in doing this.
You may want to use:
address = vc.findViewByIdOrRaise('search')
to avoid having to check for a not found address field.
Also, I guess the id is 'id/search'.
And finally a word of warning on:
address.type('india')
This is EditText.type() so you have to be sure that address is an EditText
print address.getClass()
otherwise you can use
address.touch() # to focus it
device.type('india')
or (because sometimes type() chokes)
address.touch() # to focus it
for c in 'india':
device.type(c)