How do I get ONLY Telegram Bot's first_name using get_bot()? - telegram

I'm creating a Telegram Bot using Telebot.
bot.get_me()
get_me() is the same as getme() in Telegram Bot Api.
I need to get the bot's first name.
Code above gives me:
{
"id":5519834543,
"is_bot":true,
"first_name":"BOTtle",
"username":"SomethingnotsurewhatBot",
"last_name":"None",
"language_code":"None",
"can_join_groups":true,
"can_read_all_group_messages":false,
"supports_inline_queries":false
}
In Telegram Bot Api's documentation it says that getme() returns a JSON object: https://core.telegram.org/bots/api#available-types
How do I ask it to return only first_name or username?

Apparently you can use regex
import re
import telebot
bot=telebot.TeleBot(token="ur token")
resp=str(bot.get_me())
match=re.findall("'first_name': '(.*)', 'user",resp)
print(match[0])
Here I m using telebot so regex may differ a bit as per your json response it should be like this
match=re.findall(r'"first_name":"(.*)"',resp)
You can refer to this regex cheatsheat for detailed regex info here

Related

pyTelegramBotAPI message handlers can't see photo

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.

How to send ElectroNeek RPA bot output to Telegram

I have made a ElectroNeek RPA bot that scouts the web for a particular piece of data and then I wish to send it to my Telegram. Any ideas?
Let's break up the task in two parts.
First, in order to send anything to yourself at telegram you would need to create a telegram bot and find out your telegram ID. A good tutorial on that is here. Not all of it is necessary. Read from the beginning to the words "Every Update object consists of Message objects." (You would need some basic python skills to implement this).
After you are done, you would have two numbers:
bot_token = 'XXXXXXXXXX:AAGs7Rapl-NW00ZoQMs6AP6BfhqvlXXXxXX'
bot_chatID = 'XXXXXXXXX'
Second, you would need to create the HTTP request action in your ElectroNeek flow like so:
The URL property should be a string that is comprised of variables obtained in step one, telegram URL and your message, like so:
'https://api.telegram.org/bot' + bot_token + '/sendMessage?chat_id=' + bot_chatID + '&text=' + your_variable
where "your_variable" is the variable you would like to send yourself on Telegram.

Telegram channel- how to get access_hash?

I try really hard to understand howto use Telegram api with telethon. I have some Channels in Telegram, where i want to delete older Messages. Using inputpeerchannel() i need channel_id (No Problem) and channel_hash. I cant findout howto get this channel_hash by channel_id. Thank you from germany
In order to find channel access_hash, you should resolve channel username. Original MTProto method contacts.resolveUsername#f93ccba3 gets #username and returns channel info including access_hash.
In telethon you need to invoke ResolveUsernameRequest to call the above original MTProto method. You may use this code to resolve username to access_hash:
client = TelegramClient(session_file, api_id=00000, api_hash='XXXXX')
client.connect()
response = client.invoke(ResolveUsernameRequest("your_channel_id"))
print(response.chats[0].access_hash)
client.disconnect()
There are 4 ways to get access hash:
From a Group
From username
From contact list
From chats message
So, if you have id only, there is no way to get access hash

In python-telegram-bot how to get all participants of the group?

In Python-telegram-bot how to get, if possible, the complete list of all participants of the group at which the bot was added?
You can't with current API but you could the join/exit of user members via it's API.
If you check the Message object you find :
new_chat_participant: A new member was added to the group, information about them (this member may be the bot itself)
left_chat_participant: A member was removed from the group, information about them (this member may be the bot itself)
So with this two information you can track the total number of users in your chat and who they are.
The basic strategy would be to store somewhere (like a database) the occurrences of joining and exiting of users from the group.
When a user join the chat store the object User to the storage.
When a user exit the chat delete the object User from the storage.
Well then do the logic as you need.
Also, latest API update allows you to:
telegram.get_chat_members_count(chat_id): Use this method to get the number of members in a chat.
telegram.get_chat_member(chat_id, user_id): Use this method to get information about a member of a chat.
You can combine with new_chat_participant and left_chat_participant strategy, to build information about a group.
More information here:
https://python-telegram-bot.readthedocs.io/en/stable/telegram.bot.html#telegram.Bot.get_chat_members_count
https://python-telegram-bot.readthedocs.io/en/stable/telegram.bot.html#telegram.Bot.get_chat_member
As stated by the others before, it's not possible with the bot API (for now) hence you have to go the telegram API way. Start via https://core.telegram.org/api/obtaining_api_id
I had the same problem and solved it via telethon. A snipped for you to start from:
from telethon import TelegramClient
import asyncio
api_id = 1234 # Your API_ID
api_hash = "1a2b3c456" # Your APP_ID
bot_token = "87319a123b12e321ab1cd" # (via botfather, you can alternatively sign in as a user)
goupid = -120304101020
async def get_users(client, group_id):
async for user in client.iter_participants(group_id):
if not user.deleted:
print("id:", user.id, "username:", user.username)
bot = TelegramClient('bot', api_id, api_hash).start(bot_token=bot_token)
with bot:
asyncio.get_event_loop().run_until_complete(get_users(bot, group_id))
(Example via https://gist.github.com/rokibhasansagar/d727fb30ef5a274cf536bea73260887c)

how to use telegram API codes?

i registered in https://my.telegram.org/apps and got api_hash and api_id and public key ,now i want to use this function https://core.telegram.org/method/auth.sendCode
auth.sentCode#efed51d9 phone_registered:Bool phone_code_hash:string send_call_timeout:int is_password:Bool = auth.SentCode;
auth.sentAppCode#e325edcf phone_registered:Bool phone_code_hash:string send_call_timeout:int is_password:Bool = auth.SentCode;
---functions---
auth.sendCode#768d5f4d phone_number:string sms_type:int api_id:int api_hash:string lang_code:string = auth.SentCode;
Query example
(auth.sendCode "79991234567" 1 32 "test-hash" "en")
=
(auth.sentCode
phone_registered:(boolFalse)
phone_code_hash:"2dc02d2cda9e615c84"
)
d16ff372 3939370b 33323139 37363534 00000001 00000020 73657409 61682d74 00006873 e77e812d
=
2215bcbd bc799737 63643212 32643230 39616463 35313665 00343863 e12b7901
how can i use this query example?
and what is this binaries? ==> "d16ff372 3939370b 33323139 ...."
You can't directly start to send queries to Telegram. Creating api_hash and api_id is a basic step to start with Telegram API. Hope you know that Telegram uses its own protocol called 'MTProto'. You can get the detailed discription in Telegram's official website.
As per Telegram Protocol, the Client and Server shares the 'Authorization Key' (which is used for encryption and decryption) using Diffie-Hellman algorithm. For sample please see https://core.telegram.org/mtproto/samples-auth_key. After creating the authorization key successfully, we can start to call Telegram APIs which is called as RPC queries.
You can also refer https://github.com/ex3ndr/telegram-api for implementation.
The hexadecimal data in the example is nothing but the query made by following the algorithm.
You need to start from making a valid Telegram AuthKey.
The patterns and functions you build up along the way while doing this will help you towards building the rest of your Telegram API.
You can start with this here: https://stackoverflow.com/a/32809138/44080
And them work up, step by step until you have the AuthKey as described in these links
https://core.telegram.org/mtproto/auth_key
https://core.telegram.org/mtproto/samples-auth_key
Part of the problem you will initially face is the documentation.
Working through this step by step and getting familiar with the authors writing style is a big help too.

Resources