I'm working in Telegram bot with a handler. where I need to get the user's name or users id once they use the command.
MY CODE
import telebot #Telegram Bot API
bot = telebot.TeleBot(<BotToken>)
#bot.message_handler(commands=['info'])
def send_welcome(message):
name = bot.get_me()
print(name)
bot.reply_to(message, "Welcome")
bot.polling()
However, I get only info about the bot. I can't retrieve info about the user who used handler.
OUTPUT
{'first_name': 'SPIOTSYSTEMS', 'id': 581614234, 'username': 'spiotsystems_bot', 'is_bot': True, 'last_name': None, 'language_code': None}
How do I get the user id or name of the person who uses info command?
which method i shall use? please advise.
NOTE:
My bot is linked with the Telegram group. and I've removed the Telegram TOKEN from my MVC for security reasons.
The getMe() function you are using is for getting information about the bot. But you want the name of the person who sent the message.
In the message API, there is a from attribute (from_user in python) which contains a User object, which contains the details of the person who sent the message.
So you'll have more luck with something like name = message.from_user.first_name.
try this:
message.from_user.id
message.from_user.first_name
message.from_user.last_name
message.from_user.username
or read this
https://core.telegram.org/bots/api#user
Access the user's first_name via message param passed with the method wich has the Message object, which then can access the Chat object, getting you the name via message.chat.first_name, as shown in the example below with the greet method:
#bot.message_handler(commands=['Start'])
def greet(message):
user_first_name = str(message.chat.first_name)
bot.reply_to(message, f"Hey! {user_first_name} \n Welcome To The...")
Related
This is the sync code for my discord embed, I've been trying to get the message ID of the message sent so that I can edit it, I'm trying to automate some tasks but been unsuccessful so far.
Here's the code:
embed = discord.Embed(title="Post Title")
embed.add_field(name="Req AMount", value="100")
embed.add_field(name="Return AMount", value="120")
webhook = SyncWebhook.partial(1055498127618097174, "prxoD_ZW0vO6ghrwZNhOiwI9AeLBfNYYss6MTLPkjgvAb_B3WJgWNLMMtPWYZ67GTYbn")
sending = webhook.send(embed=embed)
Any help would be appreciated thanks
In the webhook.send message, if you set the parameter wait to True, you will get a WebhookMessage object returned, which you can then use the edit/delete the message your webhook sent.
Note that the WebhookMessage object doesn't have the ID parameter but has an edit and delete methods. Typically, as webhooks are used to send messages to channels/servers you might not have a bot in/permissions for, what you can do with the returned message object is a little less.
Webhook docs send here
WebhookMessage docs here
def send_dm():
token = 'i know, just not putting my token here'
message = 'yo, dont mind just testing smth'
id = "681089525702721546"
header = {
'authorization' : token,
'user-agent' : 'i know, just not putting my user_agent here',}
payload = {'content' : message}
sd = requests.post(f"https://discord.com/api/v9/channels/{id}/messages", headers=header, data=payload)
print(sd.status_code)
So i am trying too send for fun too my friend a message with python requests but i just find out that you need to get the channel id for the direct message, but i dont know how, can someone help me finding out?
Go to Discord Settings
Click on Advanced under App Settings
Toggle Developer Mode
Go to the channel of your choice
Right-click and click on Copy-ID
Per documentation Create DM with a user (recipient_id) to return a Channel Object.
In this returned object the id key will be the id of this channel that you can use to send a message in the way you tried to.
If you want to send a message to a spesific/public channel you can get a list of all the channels via Get Guild Channels
I am trying to forward a message in telegram bot API in python . It shows "Bad Request: chat_id is empty" despite using same chat_id in sendMessage and works perfectly fine.
https://api.telegram.org/bot{BOT_TOKEN}/forwardMessage?chat_id={CHAT_ID}&from_chat_id={ID}&message_id={MID}
my problem is what is the message id and how can i find it?
for example chat id is like this number 123456789.
what does message id look like ?
You are a bot. So, people interact with you (directly or in a group). When a message is sent to your bot, you would receive a callback that includes the message details (including the chat_id, the sender chat id, the message id, and all other details). Something like this (see message->message_id and message->from_id):
{
"update_id":1111,
"message":{
"message_id":111,
"from":{
"id":1111,
"is_bot":false,
"first_name":"...",
"last_name":"...",
"username":"...",
},
"chat":{
"id":1111,
"first_name":"...",
"last_name":"...",
"username":"...",
"type":"private"
},
"date": 1111,
"text":"...."
}
}
So, you can store those details and use them to forward that message to another chat. In each chat (unique chat id), each message has a chat id (which is usually an incremental number) and by these two identifier, you can uniquely select which message from which chat should be forwarded.
Depends on where you want to access a chat_id, you can use different ways.
if you want to send a specific message to a user or bot that you don't know his chat_id, you can print a message from that user and access chat_id. Or simply forward a message from that user to #ShowChatIdBot and it returns you the related chat_id.
In fact this bot extract data from your forwarded message and gives back chat_id in that message to you.
I want send message with telethon but i dont have phone number this .
i have only #username Telegram.
with this code i can send message for my contact phone :
result = client.invoke(ImportContactsRequest([contact], replace=True))
contacts = client.invoke(GetContactsRequest(""))
for u in result.users:
client.send_message(u, 'Hi')
But i want send message to #username Telegram
You can just do the following now:
client.send_message('username', 'hello')
Old answer:
It's on the Project's wiki, quoted below.
Via ResolveUsernameRequest
An "entity" is used to refer to either an User or a Chat (which includes a Channel). Perhaps the most straightforward way to get these is by resolving their username:
from telethon.tl.functions.contacts import ResolveUsernameRequest
result = client.invoke(ResolveUsernameRequest('username'))
found_chats = result.chats
found_users = result.users
# result.peer may be a PeerUser, PeerChat or PeerChannel
See Peer for more information about this result.
I have the following code in Python to send a message to myself from a bot.
import requests
token = '123456789:ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHI'
method = 'sendMessage'
myuserid = 1949275XX
response = requests.post(
url='https://api.telegram.org/bot{0}/{1}'.format(token, method),
data={'chat_id': myuserid, 'text': 'hello friend'}
).json()
print(response)
but this returns {'description': 'Bad Request: chat not found', 'error_code': 400, 'ok': False}
What am I doing wrong? I got myuserid by sending /getid to #myidbot and I got my token from #BotFather
As #maak pointed out, you need to first send a message to the bot before the bot can send messages to you.
I was using prefix # before the value of chat_id as suggested everywhere. I removed it and it started working.
Note: if your chat id is 12345678 then you need to prefix it with -100 such that it is -10012345678.
Example Postman call:
/sendMessage?chat_id=-10012345678&text=Let's get together
If your trying to send messages to a group, you must add a ‘-‘ in front of your chat ID.
For example:
TELEGRAM_REG_CHAT_ID="1949275XX"
should be
TELEGRAM_REG_CHAT_ID="-1949275XX"
There is a way to send notifications messages to telegram. It's a bit tricky but the tutorial is great!
http://bernaerts.dyndns.org/linux/75-debian/351-debian-send-telegram-notification
I just sended a message of my apache state to a privat channel.
Works also on public channel but it's not what i wantet. As you call a script (bash) you can prepare the parameters in any script language.
Hope that helps.
For me it worked only with # prefix before channel id
I had some trouble with this after upgrading to a supergroup. The chat_id was updated and it was a bit harder to find this new id.
In the end I solved this with this by following this comment: https://stackoverflow.com/a/56078309/14213187
If you use a username, it does not require any prefix. That means the following are incorrect:
https://t.me/vahid_esmaily_ie
t.me/vahid_esmaily_ie
And this is the correct case:
vahid_esmaily_ie
If you want to use a bot message to the channel, you can refer step here
Steps:
Create a Telegram public channel
Create a Telegram BOT (for example x_bot) via BotFather
Set the x_bot as an administrator in your channel
the chat_id is #x_bot, it's a part of https://t.me/x_bot that does not add your channel name.
Telegram bots can't send messages to user, if that user hasn't started conversation with bot yet, or bot is not present in chat (if it's a group chat). This issue is not related to the library, this is simply Telegram restriction, so that bots can't spam users without their permission.
you need to first send a message to the bot before the bot can send messages to you.