How should I use parse_mode='HTML' in telegram python bot? - python

I'm trying to send a message in a channel with a bot, using Telegram API's send_photo() method. It takes a caption parameter (type String) but I can't format it through parse_mode='HTML' parameter...
If I use something like this:
send_photo(chat_id, photo, caption="<b>Some text</b>", parse_mode='HTML')
it sends the message but without any kind of formatting. Does anybody know why? Thanks

First, you need to import ParseMode from telegram like this:
from telegram import ParseMode
Then, all you need is to specify parse_mode=ParseMode.HTML. Here's a working example:
def jordan(bot, update):
chat_id = update.message.chat.id
with open('JordanPeterson.jpg', 'rb') as jordan_picture:
caption = "<a href='https://twitter.com/jordanbpeterson'>Jordan B. Peterson</a>"
bot.send_photo(
chat_id,
photo=jordan_picture,
caption=caption,
parse_mode=ParseMode.HTML
)
And we can see that it works:
Update: Actually, both parse_mode='html' (as suggested by #slackmart) and parse_mode='HTML' that you used yourself work for me!
Another Update (as per your comment): You can use multiple tags. Here's an example of one, with hyperlink, bold, and italic:
Yet Another Update: Regarding your comment:
...do I have any limitations on HTML tags? I can't use something like <img> or <br> to draw a line
Honestly,
That's what I did!
Now you're trying to format the caption of an image, using HTML, meaning you're formatting a text, so obviously, you can't use "something like <img>." It has to be a "text formatting tag" (plus <a>). And not even all of them! I believe you can only use these: <a>, <b>, <strong>, <i> and <em>.
If you try to use a text-formatting tag like <del>, it will give you this error:
Can't parse entities: unsupported start tag "del" at byte offset 148
Which is a shame! I'd love to be able to do something like this in captions of images.or something like this!

It works for me! Here's the code I'm using:
>>> from telegram import Bot
>>> tkn = '88888:199939393'; chid = '-31828'
>>> bot = Bot(tkn)
>>> with open('ye.jpeg', 'rb') as fme:
... bot.send_photo(chid, fme, caption='<b>Hallo</b>', parse_mode='html')
...
<telegram.message.Message object at 0x7f6301b44d10>
Of course, you must use your own telegram token and channel id. Also notice I'm using parse_mode='html' # lowercase

Related

Sending emojis with Selenium Python

I know that questions like this have already been asked but I have not found a clear answer that really works.
I want to send automatically dm on social medias but I want to add emojis in it. The thing is that I don't understand how do people send it because it is not allowed by the Chromedriver (it is said that only BMP is supported).
Indeed, I have found a solution to add text in an input, which is as follows :
JS_ADD_TEXT_TO_INPUT = """
var elm = arguments[0], txt = arguments[1];
elm.value += txt;
elm.dispatchEvent(new Event('change'));
"""
In my case, the place where i want to add emoji is not always an input (it can be a span or a div). Does someone have an idea about what code could help me to do that ? Thanks in advance !
If you're trying to add an emoji to a non-input field, you could set the textContent directly to it.
script = """document.querySelector('%s').textContent='%s';""" % (
css_selector,
value,
)
driver.execute_script(script)
Be sure to escape any quotes & special characters before feeding a selector in there. Eg. import re; re.escape(css_selector)
That will let you set any text on a web page element to anything, including emojis if you're not typing into an input field.

How to update a Python string in a for loop?

I am building a Discord bot using the discord.py library. The library uses the on_message(ctx) event to let us modify a message if we want to. What I would like to do is to remove the formatting and replace the user mentions with the Discord names. The text of the message looks like this:
<#!34565734654367046435> <#!34565734645354367046435> are you here?
In the ctx variable I can get the mentions as User objects from ctx.mentions and I can get the NAME and the ID of each mentioned user.
I'd like to replace the <#!34565734654367046435> with the name of the user. The result to be something like:
Name1 Name2 are you here?
This is what I have so far but it does not seem to work.
remove_formatting = utils.remove_markdown(context.content)
print(remove_formatting) # prints the very first code styled line in this question
for member in context.mentions:
remove_formatting.replace(f'<#!{member.id}>', member.name)
If I print the member.id and the member.name without doing anything else, I get the expected values. How do I update the string in this for loop?
The replace function returns a new string, it doesn't edit the existing string in place. If you edit your loop to:
remove_formatting = utils.remove_markdown(context.content)
for member in context.mentions:
remove_formatting = remove_formatting.replace(f'<#!{member.id}>', member.name)
it should work.

Pyrogram - include the username in client.copy_message

I'm creating a bot that will all a certain group of users use it for sharing images to the bot.
The bot will recieve the image and forward this to a group.
I have the bot succesfully forwarding the message with the image to the group after the user confirms but I want to append the #username or userID of the person that interacted with the bot in the forwarded message.
Possibly adding a caption with the #username or #user_id of the person who submitted the post to the bot.
FILE 1
from pyrogram import (
Client,
filters
)
#Client.on_callback_query()
async def cb(client, call):
k = call.data
msgid = int(k.split("-")[1])
chat = call.message.chat.id
await call.message._client.copy_message(-100XXXXXXGROUPID, chat, msgid,
caption="")
FILE 2
Client,
filters
)
#Client.on_message(filters.private & ~filters.caption &
~filters.command("start"))
async def copy(client, message):
chat = message.chat.id
await message.copy(-100groupc)
I've tried adding the following to the caption:
client.get_chat_members(chat)
caption=chatmember.User
I don't get any error but don't get any captions.
I am a bit lost on this looking through pyrograms docs, I don't find any good examples of how to implement something like this. I read up that the bot has to "Meet" the user first but if the user is interacting with it in the bot chat wouldn't this work?
I don't know if I already understood what are you trying to do or not but hope I got it right and here is my suggestion about the situation.
Note: You can not edit a message that is forwarded and in general, you can not edit a message that you are not sender of it.
Main Answer
I just took a look at the title you wrote and saw copy_message() function.
Actually if you take a look at the copy_message() documentation you can easily send a caption with the media you are sending.
As the documentation says:
caption (string, optional) – New caption for media, 0-1024 characters after entities parsing. If not specified, the original caption is kept. Pass “” (empty string) to remove the caption.
So just write:
Client.copy_message(chat_id, from_chat_id, message_id, caption=username)
And boom, you are sending a caption with the media you've been trying to send.
Another Solution
First of all, you have to download the picture and after that you have to upload it to wherever you need.
This makes you to be the sender of the picture and after that you can edit it and add id or username of the guy to the caption. (or you can write the cation when you are uploading the picture)
But by the way if you are sure about the fact that if you forward a message from another guy to some channel you can edit that message, give it a try and comment the result down here for us but logically this should not work.
By the way, you can edit caption of an image with edit_message_caption() function and you can send a photo with send_photo() function.
Also try to take a look at the Available Methods Documentation and see which one of the function suits you
If I understood correctly, you want users to send an image to your bot, which will then be sent to a channel with a link to the original users account?
Use the bound method message.copy() with message.from_user.mention as the caption.
#app.on_message(
filters.photo # filter for images only
& filters.user(approved_users) # only users in this list are allowed
)
def copy_to_channel(_, message):
message.copy( # copy() so there's no "forwarded from" header
chat_id=target_chat, # the channel you want to post to
caption=message.from_user.mention # mentions the posting user in the new message
)

How to get formatted text with entities?

I need some help with telethon:
I have text from telethon message. Example: 'some text message'
And i have an entity. Example: {"_": "MessageEntityBold", "offset": 5, "length": 4}
I need some method or tip to get formated text like this: '''some <b>text</b> message'''
The Message.text returns the text formatted using the current parse mode of the client. By default, this is Telegram's markdown, which means you would get some **text** message with the following code:
print(message.text)
Please note that since it currently relies on the client.parse_mode, you cannot use the .text property for messages returned by raw API since the results are not modified there. Instead, the message must be fetched with a friendly method or through events.

how to pass value from output to a string in python

I've been trying to make an application in python and I'm new to python.
Well, what I actually want to do is that . I want the feedparser to read the values from an RSS of a website... say reddit... and then I want to make that output as a stringand pass the value further to my code... my code right now..
import feedparser
import webbrowser
feed = feedparser.parse('http://www.reddit.com/.rss')
print feed['entries'][1]['title']
print feed['entries'][1]['link']
It is working right now.. it parses the feed and I get the output I want... Now, I want to use the "link" from the "print feed['entries'][1]['link'] " and use it in the code further...
how can I do so..? To be more specific.. I want to open that URL in my browser...
I concluded to something like this..
import feedparser
import webbrowser
feed = feedparser.parse('http://www.reddit.com/.rss')
print feed['entries'][1]['title']
print feed['entries'][1]['link']
mystring = 'feed['entries'][1]['link']'
webbrowser.open('mystring')
It is of course not working... Please Help... if you need to know anything else.. please let me know...
This is Reddit specific so it won't work on other RSS feeds but I thought this might help you.
from __future__ import print_function
import praw
r = praw.Reddit("my_cool_user_agent")
submissions = r.get_front_page()
for x in submissions:
print("Title: {0} URL: {1} Permalink: {2}".format(x, x.url, x.permalink))
print ("------------------------------------------------------------")
For Reddit there are 2 URLs that you might be interested in: the actual link that is submitted (the 'external' link... think imgur, etc) and the permalink to the Reddit post itself.
Instead of passing the feed[entries][1][link] as a string, just pass the value inside to the webbrowser.
Example -
webbrowser.open(feed['entries'][1]['link'])

Categories

Resources