Open another Telegram chat/group/channel using Bot - python

I suspect it may be rather kid question – but anyway.
How to open another Telegram chat or group or channel using pyTelegramBotAPI? I want to forward the user (not message, the user himself) to another channel if he clicks certain button.
I saw content type migrate_to_chat_id in Message class declaration. Should I use it? If so, how to get an id of channel I need? It won't send any message to my bot.
I would better use "t.me/..." url.

Partly solved.
Speaking about the buttons, it is indeed easy. You just use named parameter url= in InlineKeyboardButton() method.
For other cases. You need to open another channel(s) from function depending on several conditions for instance. Still don't know. Import requests and make GET request? I suspect that something for it should already be in pyTelegramBotAPI, but searching in lib files wasn't successful.

Related

How do I get the other user's id from a chat in Telegram?

I wonder how I can find the id of a certain user I started a regular or secret chat with.
Example:
dialogs=client.get_dialogs()
for dialog in dialogs:
print(dialog.peerUser_id)
What can substitute the peerUser_id?
Note: I use Telethon Library
You can't. Secret chats are per device and as such, you can't get any information about It from another device. the only device that sees it is the one that started it so if you didn't start it yourself you won't be able to see it.
SOLVED.
To find out the user id from a private conversation (which is a Dialog in the example) you can use :
dialog.message.peer_id.user_id

How to use parse mode in telegram send message bot in Python

I'm pretty new to making bot thing so I have several questions I want to ask regarding this:
I'm using a bot to send message by
def send_message(chat_id, msg):
url = f"https://api.telegram.org/bot{bot_token}/sendMessage?chat_id={chat_id}&text={msg}"
requests.get(url)
send_message(chat_id,msg)
By this, I can send message and I want to beautify the result by using parse_mode but I don't know where to put in in url to make it work.
I'm alternate to using Telethon. I can use it to send message to individual and group by user name and group invite link, but when I try to send it to channel by:
client.send_message(entity='my channel name', message=message)
When I try to run it, it return Cannot find any entity corresponding to "Test channel".
I also try
destination_channel_username='test_ali3'
entity=client.get_entity(destination_channel_username)
client.send_message(entity=entity,message="Hi")
but it require my channel access_hash, how can get it, or are there any other way to send message to channel.
I know Telegram bot API have function like sendMessage or bot.sendMessage that also can do the job, but somehow I can't call it, which packages should I install and/or import.
Thanks a lot!
This should do the trick:
def send_message(chat_id, msg, parse_mode):
url = f"https://api.telegram.org/bot{bot_token}/sendMessage?chat_id={chat_id}&text={msg}&parse_mode={parse_mode}"
requests.get(url)
TBH I'm not too familiar with telethon, but that library is mainly intended for so called userbots. that means that it uses the API that also the Telegram app uses and because of that, it's often times more involved than just the plain bot api.
To use the Bot API in Python, I can recommend the package python-telegram-bot, see https://python-telegram-bot.org. Disclaimer: I'm currently the maintainer of that package. There are also other python packages for the bot api, see e.g. https://core.telegram.org/bots/samples#python

How can I get the number of messages sent by a user in a discord server without discord.py?

Using discord's search function manually, you can enter something like from:user#3456 and it will show you how many messages they've sent on the server (at least, messages you have access to).
I've been told there is no way to get this information through discord.py, but is there really no way to get that data at all? Would I have to resort to a web scraping tool?
To be clear, I have looked at history() already. What I'm looking for is a way to access the search function that Discord already has.
This is actually possible using discord.TextChannel.history. Here is an example:
userMessages = []
userID = 1234567890 # Change this to the ID of the user you are looking messages for
channelID = 1234567890 # Change this to the channel ID of the messages you want to check for
channel = client.get_channel(channelID)
user = discord.utils.find(lambda m: m.id== userID, channel.guild.members)
async for message in channel.history():
if message.author == user:
userMessages.append(message.content)
print(len(userMessages)) # Outputs total user messages
Make sure you replace 1234567890 with the corresponding IDs.
I've added an array which also shows all the user messages, if you prefer you can remove that and have it increment a counter instead.
I solved this in a kind of hacky way by searching with a from:username query in the Discord app, looking at the http request with Chrome DevTools, and finally recreating the request with the python module requests.
In Discord in a browser, you can open DevTools with the f12 key.
In DevTools, navigate to the Network tab.
I'd suggest to fill in the search query (but don't hit enter), then open devtools, then hit enter on the search. Otherwise there will be a lot of http requests that pop up as you type.
Then, you find the request with a name that looks like "search?author_id=1234567890". If you click on that request, you can see the details necessary to recreate it.
The key parts of the http request you need to use are the Request Headers section and the Request URL under the General section, all in the Headers tab that pops up when you first click on the request, and the Response tab to see what your response will look like.
The accept-encoding attribute of the Request Headers includes br, but this seems to jumble the result. Keeping it to just gzip, deflate works for me.
Using the requests python module this should be pretty easy to set up. So long as br is not listed in accepted-encoding, you should be able to use the json() method of requests, and for the particular problem of finding the total messages sent by the user (whose id you must insert into the request URL), it's simply accessible with my_request_variable.json()['total_results'].
The main thing to watch out for is the authorization request header. This is unique to the user (you, unless you do all this from someone else's account) and you can't substitute in a discord bot's token, unfortunately.

Multiplayer call to Telegram bot

I'm writing a telegram-bot. It checks the email box(common to all), and if it finds the set parameters then returns some information to the user and delete this email that contains this parameters. So the problem is this: when I call this bot alone, everything's allright, but if I cal it from several accounts at the same time, it doesn't work correctly. It either doesn't send the information, or sends it incorrectly. It sends the info which belongs to other user. I can't solve this? Can anybody advise me somethin? Sorry for my Ruslish)))

telegram bot image from url - undesired cache

I am working on a telegram bot that displays images from several webcams upon request. I fetch the images from urls and then send to the user (using bot.sendPhoto() ) My problem is that for any given webcam the filename does not change and it seems that the photo is sent from telegram's cache. So it will display the image from the first time that image was requested.
I have thought about downloading the image from the url, saving with a variable name (like a name with a timestamp in it) then sending it to the chat, this seems like an inelegant solution and was hoping for something better. Like forcing the image not to be cached on the telegram server.
I am using the python-telegram-bot wrapper, but I am not sure that it's specific to that.
Any ideas? I have tried searching but so far am turning up little.
Thanks in advance.
I had the same problem too, but i've found the simplest solution.
When you call the image, you have to add a parameter with timestamp to the image link.
Example:
http://www.example.com/img/img.jpg?a=TIMESTAMP
Where TIMESTAMP is the timestamp function based on the language you are using.
Simple but tricky ;)
I think the best way is to do the same as we do in React where also, same URL calls are first checked in the cache.
If you are using Python the best way is:
timestamp = datetime.datetime.now().isoformat()
# Above statement returns like: '2013-11-18T08:18:31.809000'
pic_url = '{0}?a={1}'.format(img_url, timestamp)
Hope that helps!
I had the same problem. I wanted to create a bot which sends an image taken by a webcam of a ski slope (webcam.example.com/image.jpg). Unfortunately, the filename and so the url never updates and telegram always sends the cached image. So I decided to alter the url passed to the api. In order to achieve this, I wrote a simple php site (example.com/photo.php) which redirects to the original url of the photo. After that, I created a folder (example.com/getphoto/) on my webspace with a .htaccess file inside. The .htaccess redirects all request in this folder to the photo.php site which redirects to the image (webcam.example.com/image.jpg). So you could add everything to the url of the folder and still get the picture (e. g. example.com/getphoto/42 or example.com/getphoto/hrte8437g). The telegram api seems to cache photos by url, so if you add always another ending to the url passed to the api, telegram doesnt use the cached version and sends the current image instead. The easiest way to always change the url is by adding the current date to it.
example.com/photo.php
<?php
header("Location: http://webcam.example.com/image.jpg");
die();
?>
example.com/getphoto/.htaccess
RewriteEngine on
RewriteRule ^(.*)$ http://example.com/photo.php
in python:
bot.sendPhoto(chat_id, 'example.com/getphoto/' + strftime("%Y-%m-%d_%H-%M-%S", gmtime()))
This workaround should also work in other languages like java or php. You just need to change the way to get the current date.

Categories

Resources