python telegram bot: why are digits a link to phone number? - python

Sending text/markdown with Python-Telegram-Bot, all digit groups are rendered as links to phone numbers like in
Clicking on 12345 it jumps to the phone call keyboard. How can I avoid this behavior, rendering 12345 as normal text (not a link)?
I went through the documentation but cannot find any reference to this particular issue.
This is the test code:
import telegram
from telegram.ext import Updater, CommandHandler
TOKEN="token_here"
def start_function(update, context):
update.message.reply_text("Test 12345", parse_mode=telegram.ParseMode.MARKDOWN)
bot = telegram.Bot(token=TOKEN)
updater = Updater(token=TOKEN, use_context=True)
dispatcher = updater.dispatcher
dispatcher.add_handler(CommandHandler("start", start_function))
updater.start_polling()
Any pointer to docs or examples is welcome. Thank you in advance.

MarkDown
Wrap the number in ``(backtick);
Test: `12345`
HTML
Wrap the number in a <code></code> block;
Test: <code>12345</code>
MarkDown example (first witout ``, second request;):
&text=Test: `12345`&parse_mode=MarkDown

Related

How to get caption from Telegramm message(Pyrogram)

I'm newbie at Python. I want to parse certain dialog(contains only captions to pics) with Pyrogram. But if i use iter_history() methog it returns none if message contains pic+text.Like that.
import asyncio
from pyrogram import Client
app = Client("my_acc")
target = "dialog_example" # "me" refers to your own chat (Saved Messages)
with app:
for message in app.iter_history(target):
print(message.text)
None
Process finished with exit code 0
message.text is a message's text. If you want the caption of a message (or document rather), access message.caption.

pyTelegramBotAPI disable link preview

Currently writing my first bot using pyTelegramBotAPI. I want to disable link previews on certain messages. How do I do this?
It looks like there is an disable_web_page_preview parameter on the sendMessage method.
tb = telebot.TeleBot(TOKEN)
tb.send_message(123456, "Hi <link>", disable_web_page_preview=True)
Original code;
def send_message(token, chat_id, text, disable_web_page_preview=None, reply_to_message_id=None, reply_markup=None,
parse_mode=None, disable_notification=None):
Try using link_preview/disable_web_page_preview parameter.
client.send_message('chat_name', '[link](example.com)', parse_mode = "Markdown", link_preview=False)
To me this works:
client.send_message(chat_name, msg, link_preview=False)
(Python 3.8, Telethon 1.24)

How to send bold text using Telegram Python bot

I am writing a telegram bot in Python. I want to send messages with bold letters. I tried to inclose message inside both * and **, but it does not solve the problem.
Is there a function for mark up or HTML formatting or a way to do it?
You should use:
bot.send_message(chat_id=chat_id, text="*bold* Example message",
parse_mode=telegram.ParseMode.MARKDOWN)
Or:
bot.send_message(chat_id=chat_id, text='<b>Example message</b>',
parse_mode=telegram.ParseMode.HTML)
More info at:
https://github.com/python-telegram-bot/python-telegram-bot/wiki/Code-snippets#message-formatting-bold-italic-code-
This is a little bit late. But i hope to be helpful for others:
import telepot
token = 'xxxxxxxxxxxxxxx' # Your telegram token .
receiver_id = yyyyyyyy # Bot id, you can get this by using the next link :
https://api.telegram.org/bot<TOKEN>/getUpdates. Note that you should
replace <TOKEN> with your token.
bot = telepot.Bot(token)
message = "*YOUR MESSAGE YOU WENT TO SEND.*" #Any characters between ** will be
send in bold format.
bot.sendMessage(receiver_id, message , parse_mode= 'Markdown' )

How can I download the chat history of a group in Telegram?

I would like to download the chat history (all messages) that were posted in a public group on Telegram. How can I do this with python?
I've found this method in the API https://core.telegram.org/method/messages.getHistory which I think looks like what I'm trying to do. But how do I actually call it? It seems there's no python examples for the MTproto protocol they use.
I also looked at the Bot API, but it doesn't seem to have a method to download messages.
You can use Telethon. Telegram API is fairly complicated and with the telethon, you can start using telegram API in a very short time without any pre-knowledge about the API.
pip install telethon
Then register your app (taken from telethon):
the link is: https://my.telegram.org/
Then to obtain message history of a group (assuming you have the group id):
chat_id = YOUR_CHAT_ID
api_id=YOUR_API_ID
api_hash = 'YOUR_API_HASH'
from telethon import TelegramClient
from telethon.tl.types.input_peer_chat import InputPeerChat
client = TelegramClient('session_id', api_id=api_id, api_hash=api_hash)
client.connect()
chat = InputPeerChat(chat_id)
total_count, messages, senders = client.get_message_history(
chat, limit=10)
for msg in reversed(messages):
# Format the message content
if getattr(msg, 'media', None):
content = '<{}> {}'.format( # The media may or may not have a caption
msg.media.__class__.__name__,
getattr(msg.media, 'caption', ''))
elif hasattr(msg, 'message'):
content = msg.message
elif hasattr(msg, 'action'):
content = str(msg.action)
else:
# Unknown message, simply print its class name
content = msg.__class__.__name__
text = '[{}:{}] (ID={}) {}: {} type: {}'.format(
msg.date.hour, msg.date.minute, msg.id, "no name",
content)
print (text)
The example is taken and simplified from telethon example.
With an update (August 2018) now Telegram Desktop application supports saving chat history very conveniently.
You can store it as json or html formatted.
To use this feature, make sure you have the latest version of Telegram Desktop installed on your computer, then click Settings > Export Telegram data.
https://telegram.org/blog/export-and-more
The currently accepted answer is for very old versions of Telethon. With Telethon 1.0, the code can and should be simplified to the following:
# chat can be:
# * int id (-12345)
# * str username (#chat)
# * str phone number (+12 3456)
# * Peer (types.PeerChat(12345))
# * InputPeer (types.InputPeerChat(12345))
# * Chat object (types.Chat)
# * ...and many more types
chat = ...
api_id = ...
api_hash = ...
from telethon.sync import TelegramClient
client = TelegramClient('session_id', api_id, api_hash)
with client:
# 10 is the limit on how many messages to fetch. Remove or change for more.
for msg in client.iter_messages(chat, 10):
print(msg.sender.first_name, ':', msg.text)
Applying any formatting is still possible but hasattr is no longer needed. if msg.media for example would be enough to check if the message has media.
A note, if you're using Jupyter, you need to use async directly:
from telethon import TelegramClient
client = TelegramClient('session_id', api_id, api_hash)
# Note `async with` and `async for`
async with client:
async for msg in client.iter_messages(chat, 10):
print(msg.sender.first_name, ':', msg.text)
Now, you can use TDesktop to export chats.
Here is the blog post about Aug 2018 update.
Original Answer:
Telegram MTProto is hard to use to newbies, so I recommend telegram-cli.
You can use third-party tg-export script, but still not easy to newbies too.
You can use the Telethon library. for this you need to register your app and connect your client code to it (look at this).
Then to obtain message history of a entry (such as channel, group or chat):
from telethon.sync import TelegramClient
from telethon.errors import SessionPasswordNeededError
client = TelegramClient(username, api_id, api_hash, proxy=("socks5", proxy_ip, proxy_port)) # if in your country telegram is banned, you can use the proxy, otherwise remove it.
client.start()
# for login
if not client.is_user_authorized():
client.send_code_request(phone)
try:
client.sign_in(phone, input('Enter the code: '))
except SessionPasswordNeededError:
client.sign_in(password=input('Password: '))
async for message in client.iter_messages(chat_id, wait_time=0):
messages.append(Message(message))
# write your code

How to receive file_id through python-telegram-bot?

I'm making a Telegram bot using python-telegram-bot, and I need some way to receive voice messages. For that, I need to download them, and to do that, I have to get their file_ids. However, the MessageHandler handles... well, messages, and Handler gives me a NotImplementedError. Is there a way to get the file_id?
I know this question is old but I was facing a problem with this in the latest version (12+)
So it appears that the bot- pass_user_data in the callback function is deprecated and from now on you should use context based callbacks.
CallbackContext is an object that contains all the extra context
information regarding an Update, error or Job.
to the new style using CallbackContext:
def voice_handler(update: Update, context: CallbackContext):
file = context.bot.getFile(update.message.audio.file_id)
file.download('./voice.ogg')
You can read more in the Transition-guide-to-Version-12.0
The easiest way to download voice messages is to register a MessageHandler with a voice filter. The Docs provide more information on Filters and the voice module.
import telegram
from telegram.ext import Updater
def voice_handler(bot, update):
file = bot.getFile(update.message.voice.file_id)
print ("file_id: " + str(update.message.voice.file_id))
file.download('voice.ogg')
updater = Updater(token='TOKEN')
dispatcher = updater.dispatcher
dispatcher.add_handler(MessageHandler(Filters.voice, voice_handler))
In version 13+, you need to use update.message.voice.file_id instead of update.message.audio.file_id. So the code will be:
def voice_handler(update: Update, context: CallbackContext):
file = context.bot.getFile(update.message.voice.file_id)
file.download('./voice.ogg')
I'll show you an example with a photo file, but it works for any file (you'll just need to change the parameters)
from telegram.ext import Updater, CommandHandler
from telegram.ext.callbackcontext import CallbackContext
from telegram.update import Update
def start (update: Update, context: CallbackContext):
# getting chat_id:
chatID = update.effective_chat.id
# sending the photo to discover its file_id:
photo1 = context.bot.send_photo(chat_id=chatID, photo=open('photo1.jpg','rb'))
photo1_fileID = photo1.photo[-1].file_id
context.bot.send_message(chat_id=update.effective_chat.id, text=('file_id photo1.jpg = ' + photo1_fileID))
def main():
updater = Updater(token='TOKEN', use_context=True)
dispatcher = updater.dispatcher
dispatcher.add_handler(CommandHandler('start', start))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()

Categories