How to send message in telegram bot


visual studio code - How can I send a message to someone with my telegram bot using their Username

Asked

Modified 1 year, 11 months ago

Viewed 145k times

44

New! Save questions or answers and organize your favorite content.
Learn more.

I am using the telepot python library, I know that you can send a message when you have someone's UserID(Which is a number). I wanna know if it is possible to send a message to someone without having their UserID but only with their username(The one which starts with '@'), Also if there is a way to convert a username to a UserID.

  • visual-studio-code
  • python
  • telegram
  • telegram-bot
  • python-telegram-bot

2

  1. Post one message from User to the Bot.
  2. Open https://api. telegram.org/bot<Bot_token>/getUpdates page.
  3. Find this message and navigate to the result->message->chat->id key.
  4. Use this ID as the [chat_id] parameter to send personal messages to the User.

1

It is only possible to send messages to users whom have already used /start on your bot. When they start your bot, you can find update.message.from.user_id straight from the message they sent /start with, and you can find update.message.from.username using the same method. In order to send a message to "@Username", you will need them to start your bot, and then store the username with the user_id. Then, you can input the username to find the correct user_id each time you want to send them a message.

You can't send message to users using their username that is in form of @username, you can just send messages to channel usernames which your bot is administrator of it. Telegram bot api uses chat_id identifier for sending messages. If you want to achieve chat_id of users, you can use telegram-cli, but it's not easy at all because that project is discontinued and you should debug it yourself. in your case you should do following command:

> resolve_username vahid_mas 

and the output will be something like this:

{ "user": { "username": "Vahid_Mas", "id": "$010000006459670b02c0c7fd66d44708", "last_name": "", "peer_type": "user", "print_name": "Vahid", "flags": 720897, "peer_id": 191322468, "first_name": "Vahid", "phone": "xxxxxxx" }, "online": false, "event": "online-status", "state": -1, "when": "2017-01-22 17:43:16" } 

1

As the user you want to learn the ID of, send a message of any content to @JsonDumpBot. It will reply the whole JSON element that it receives from Telegram, including the ID of the user:

It's totally not safe to use other telegram versions available on internet, but I've seen that Telegram Plus has a ability to show you the chat_id of the user in their profile, even tho you don't have their contact.

Another way to extract chat_id of that particular user is that you have the phone number of that account, save it as your contact, then share it to this bot. It's easy to code it yourself but you can forward something from that user to this bot too, if you want to recieve the chat_id.

urmurmur has also mentioned another way. I haven't checked it yet but seems to be interesting.

Sign up or log in

Sign up using Google

Sign up using Facebook

Sign up using Email and Password

Post as a guest

Email

Required, but never shown

Post as a guest

Email

Required, but never shown

How to Send Message in Telegram

Telegram is a cloud-based messaging app that adds a lot of convenience to your communication. The platform lets you transfer conversations between computers, smartphones, and tablets. It also provides great security, owing to the secret chats feature. But how exactly do you send messages on Telegram?

In this entry, we’ll go through all intricacies of Telegram messaging.

How to Send a Message on Telegram

Quick Links

  • How to Send a Message on Telegram
  • How to Send a Message to Myself on Telegram
  • How to Send a Message to a Bot on Telegram
  • How to Send a Voice Message on Telegram
  • How to Send a Direct Message on Telegram
  • How to Send a Video Message on Telegram
  • How to Send a Message on Telegram With an API
  • What to Do if Telegram Fails to Send a Message
  • What to Do if Telegram Is Unable to Send a Message
  • Additional FAQs
    • How Can I Send Message to Telegram API?
    • Can Telegram Send SMS?
  • Step Up Your Chat Game

Sending a message on Telegram is just as easy as with other similar apps:

  1. Download and install the app from Google Play or App Store.
  2. Type in your phone number and enter the verification code Telegram sends you.
  3. Add a picture and your name.
  4. Allow Telegram to access your contacts list.
  5. Hit “Contacts” in the lower part of your screen, and you’ll see a list of friends using the app.
  6. Select a friend and use the text field to type and send your message.

How to Send a Message to Myself on Telegram

You can send a message to yourself with the “Saved Messages” function:

  1. Open the app and go to the menu in the top-left corner.
  2. Press “Saved Messages.”
  3. Type your message here, and you’re all done.

How to Send a Message to a Bot on Telegram

Once Telegram bots are set up, users can interact with them by sending commands, messages, or requests. Here’s how the process works:

  1. Start Telegram and enter your log-in information.
  2. Type in “@Botfather” in your search bar and choose the bot that appears in the search results.
  3. Press the “Start” button to activate the bot.
  4. Enter “/newbot” and send the command.
  5. Select a name and username for the bot. Users will be able to find their bot by searching for its username, but it mustn’t overlap with other bots’ usernames.
  6. Once you’ve chosen an appropriate name for the bot, it will be created. You’ll then receive a link to the bot, suggestions on setting up the profile picture, commands for managing the bot, and some other details.
  7. Follow your link and you’ll be able to send your bot a message the same way you do with your friends.

How to Send a Voice Message on Telegram

If you’re too busy to type, sending a voice message to your friend will save you some time:

  1. Open Telegram and go to your chat windows.
  2. Choose a chat and tap the microphone symbol in the lower-right corner.
  3. Hold the symbol and start talking.
  4. Once you’re done, release the symbol, and the voice message will be sent.

How to Send a Direct Message on Telegram

Direct messages are also referred to as private messages on Telegram. Sending them is relatively straightforward:

  1. Launch Telegram.
  2. Press “New message.”
  3. Select the recipient of the message.
  4. Press the username of the person to open your chat with them.
  5. Type in your message.
  6. Hit the “Send” button, and you’re good to go.

How to Send a Video Message on Telegram

Telegram doesn’t lag behind other platforms in terms of the media you can send through the app. One of your options is a video message:

  1. Start the app and open a chat.
  2. Hit the microphone symbol to launch camera mode.
  3. Hold the camera symbol and record your message.
  4. Release your recording button, and the message will be sent.

How to Send a Message on Telegram With an API

Using an API to send your Telegram message is a bit more complex. You’ll require the services of a bot:

  1. Find the Botfather bot by looking it up in your search box.
  2. Once you’ve set up your bot, type in “/newbot” in the chat box. You’ll then be asked to name your bot and give it a username. You’ll then receive a link to the bot and your API token.
  3. Click the link to reach the box where you’ll receive your messages. Since bots are designed not to send spam, they can’t start a chat, meaning that you’ll need to send a message first to allow the bot to text you back.
  4. You now need to call Telegram’s API to obtain your chat_id. You have two methods here.
  5. The first one comes down to reading the text you sent using curl and its getUpdates approach: curl https://api.telegram.org/bot%7BYOUR_API_KEY_HERE%7D/getUpdates
  6. Alternatively, you can use Python 3:
    • >>> import requests
    • >>> token = {YOUR_API_KEY_HERE}
    • >>> url = f'https://api. telegram.org/bot{token}/getUpdates'
    • >>> requests.post(url).json()
  7. You should then receive your JSON payload: {"ok":true,"result":[{"update_id":12671344, "message":{"message_id":30,"from":{"id":{YOUR_ID},"is_bot":false,"first_name": "{YOUR_NAME}" ,"username":"{YOUR_USERNAME}","language_code":"en"},"chat":{"id":{YOUR_CHAT_ID},"first_name":"{YOUR_FIRST_NAME}","username":"{YOUR_USERNAME}","type":"private"},"date":1560719493,"text":"{YOUR_SENT_MESSAGE}"}}]}
  8. Use {YOUR_CHAT_ID} number that consists of approximately nine numbers.
  9. You’ll now be able to send a message with the sendMessage function: curl -d chat_id={YOUR_CHAT_ID} -d text="test msg from curl" https://api.telegram.org/bot{YOUR_API_KEY_HERE}/sendMessage
  10. Another option is Python 3:
    • >>> import requests
    • >>> token = {YOUR_API_KEY_HERE}
    • >>> url = f'https://api. telegram.org/bot{token}/sendMessage'
    • >>> data = {'chat_id': {YOUR_CHAT_ID}, 'text': 'python msg'}
    • >>> requests.post(url, data).json()
  11. You’ve now successfully sent a message using Telegram’s API.

What to Do if Telegram Fails to Send a Message

If your Telegram doesn’t send a message for some reason, two simple solutions might do the trick:

  1. Return to Telegram’s front page and head back to your message.
  2. Alternatively, restart the app, return to the message and try to re-send it.

What to Do if Telegram Is Unable to Send a Message

If you can’t send your message and the problem persists, your best option is to reach out to Telegram’s customer support. You can describe your issue here, enter your phone number, and leave your email address. Hopefully, their team will feed you a viable solution.

Additional FAQs

How Can I Send Message to Telegram API?

Sending a message to Telegram’s API requires you to set up a bot. Next, you’ll need to use curl or Python 3 to generate your chat_id and send your message using the sendMessage command.

Can Telegram Send SMS?

Unfortunately, you can’t send an SMS using Telegram. The app still doesn’t support this feature.

Step Up Your Chat Game

If you thought you might not be into Telegram due to cumbersome messaging features, all your worries are now dispelled. The app is easy to use, and once you’ve activated it, texting is just as easy as on any other platform. Best of all, you can send videos, voice messages, and even set up bots and issue various commands. The options are nearly endless.

Have you set up your Telegram profile? Do you find the interface user-friendly? Are all the features easily accessible? Let us know in the comments section below.

How to Rename Columns in the Google Sheets App

Read Next 

How to send a message to Telegram


Here we tell you how to send private messages to Telegram using a bot.

If you want to send messages not to private messages, but to a group in Telegram, then refer to this instruction.

How to set up sending messages

Build a script

To send something to Telegram, we first need to write information to a variable. You can collect several parameters, write them into variables, and transfer all these variables to Telegram. Before sending data, you must have a script section with writing to variables.

Complete this lesson to build a script.

After completing the lesson, you will have 5 variables:

  • for the name
  • for last name
  • for phone
  • for email
  • for service type

Publish the bot on Telegram

Follow the instructions to publish the bot on Telegram.

If you have already published a bot in Telegram, go to the next step.

Get chat_id

In order to receive a message in Telegram, the bot must know who to send it to. You can get chat_id of your account (or the account of the person you want to send this information to) so that you can send messages using the bot.

To get chat_id , create a new screen in the script with the text:

$rawRequest.message.from.id

Place this screen at the beginning of the script so that this screen is in the upper left corner . Thus, this screen will be the first one when the bot starts.

Publish the bot

Click Publish and wait for the message that the script has been published on the Telegram channel.

Test the bot

Now go to your Telegram bot ( is not in the test widget! ) and send to the bot:

/start

If you want messages to be sent not to you, but to another person, then simply send this person a link to the bot. If this user communicates with this bot for the first time, the bot will immediately send the value chat_id . If this user has already chatted with this bot before, then ask the user to send /start to the chat to get the chat_id.

The bot will send you the required value:

Copy and paste the number sent by the bot into notepad .

Remove the screen with text $rawRequest.message.from.id . He is no longer needed.

Send data

The next step is to send the data received from the client. To do this, in the script, after collecting all the necessary information , there must be an HTTP request block. Several variables can be passed at once with a single request:

The block must be formatted as follows:

Method
GET

Formation of URL

To create a URL, copy the line into notepad: https://api. telegram.org/bot/sendMessage

Then go to Telegram to the Botfather channel and copy your bot token, which was generated when you published the channel:

In a notebook select 9000

and instead of insert a tokeene from a tokeene Telegram:

You will get something like this:

Now select the entire line and paste it into the URL field of the HTTP request in Aimylogic

Formatting the field
BODY

In BODY we need to specify:

  • the value chat_id that we received earlier

  • all the variables that we have previously collected in the script.

If you repeated the lesson on collecting contact data, then in the script you received the following information:

Your name: $name Your last name: $lastname Your phone: $PHONE Your email: $EMAIL Type of service: $service

That's why we use these variables now.

So, you need to insert the value chat_id and list the variables that were in the script before sending.

Pay attention to indentation and punctuation! We recommend not typing, but copy and paste.

{ "chat_id": 123456789, "text": "Customer name: $name $lastname, phone number: $PHONE, email: $EMAIL, Service type: $service"}

Press Save .

Done, we have issued an Http request to send data.

Check the status of the submission

From the "Completed successfully" logic, add a link to a new screen containing a message that the data was successfully sent. For example, “Thank you, your data has been successfully sent!”

From the logic “Completed with an error”, we make a connection with the screen containing the text block “Error $httpStatus ”. This block will help us understand what the problem is if the http request is not successful.

Test scenario

Press Test and talk to the bot.

As a result of the dialogue, the necessary information should come to Telegram.

Note that the bot will send a message to your conversation with the bot. If you expect to receive a private message from some other account, you may be confused by this behavior. But in the future, when other people write to the bot, and you will receive messages from the bot, it will be more clear to you what is happening. Ask another person to send their name and phone number to the bot, and then you will receive a message from the bot.

Troubleshooting

You click Test and the bot throws an error.

Check if you are using $rawRequest in the script to get the name. If yes, then you need to test in the Telegram channel. In the test widget, the error will be expected to fall out, as the bot is trying to get information from a channel that does not exist.

"Error -1"

Check that the URL in the http request is correct. There may be a space in the URL itself or at the end of the URL, or an invalid character may have been inserted by mistake.

"Error 400"

  1. Check that the http request is formatted correctly. Try deleting the Telegram bot at BotFather , recreate and use the newly generated token.

  2. Check the formatting of the field BODY (syntax).

Example of correct field design

BODY :
  • First and last line must contain only curly braces

  • Must be indented (you can press Tab or press Spacebar four times)

  • "chat_id": should be written like this (check for typos, or better yet, copy and paste):

    "chat_id":

  • The value of chat_id should not be 123456789, but the real value you copied in step 3 (123456789 is the example for the tutorial)

  • A string containing "chat_id": must end with a comma

  • Colons must be followed by spaces

  • The value of the transmitted message text must be in the following quotes: " "

    How to send a message to a Telegram group


    You can not only use bots Aimylogic to send private messages to Telegram , but also add them to group chats in Telegram .

    We're assuming you've already created a bot script and know how to publish it to a Telegram channel, so here we'll only cover how to send messages to a group chat.

    Prepare the script

    First of all, as a start screen, add a text block to the script, into which you copy and paste: $rawRequest.message.chat.id

    This screen must be topmost and leftmost for the bot to display this message first.

    Add variables to the script

    Also, your script must be able to send data to Telegram. To do this, they need to be written to a variable.

    For example, let's add a block text to $var , with which we will write a message to the variable $message :

    Link "Transition after entering $message " to block Http request . The request method is GET .

    Now create the request URL. Instead, you will need to paste the channel token that you received in BotFather into the URL.

    https://api.telegram.org/bot/sendMessage

    In the BODY field of the request, insert the following:

     { "chat_id": chat_id_number, "text": "$message" } 

    chat_id_number will need to be replaced with the value that you will receive at the bot activation stage in the group at Telegram .

    You can also send any other variables you receive in the script. For example, like this:

     { "chat_id": chat_id_number, text: "client name: $name, phone: $PHONE, feedback: $feedback" } 

    If you are sending other variables, make sure they are actually filled in the script before sending the request.

    Prepare an error message

    Associate the "Completed with an error" variant with block Text where to write error $httpStatus

    eg Thank you, your application has been sent!

    Prepare a Telegram group for the bot

    Now you need to create a group to which you want to add the bot and activate it.

    Create a group in Telegram

    Create a group in Telegram by selecting Create group from the menu and give it a name:

    Add at least one member to the group and click Create and then add your bot to the group. To do this, click Add members . Type the name of the bot in the search, select the bot and click Invite :

    Activate Bot

    Send the command /start to the group. The bot will send you a message from the character set. You will need this value, including the character - , later:

    Add the bot to an existing group

    If you already have a group in Telegram that you want to add the bot to, you need to:

    • Create a chat with the bot
      • The link to the bot is in BotFather , in the message in which you received the bot token
    • Go to the bot dialog menu and select Add to group . Follow directions
    • Now you need to allow the bot to read messages in the group. For this:
      • Go to BotFather
      • Write command /mybots
      • Select the desired bot
      • Go to Bot Settings → Group Privacy
      • Select Turn off
      • The phrase Privacy mode is disabled for Bot 9 should appear0470

    Delete $rawRequest

    Return to the bot script.

    Now you can delete the block that contains $rawRequest.message.chat.id .

    Publish the bot

    Publish the bot in Telegram and wait for publication:

    Test the bot

    Now write to the Telegram bot (not in a group). The link to the bot is in BotFather , in the message in which you received the bot token.

    Start a new session with /start , send a message to the bot and make sure it comes to the group:

    If your users write to the bot, messages from them will also be published in the Telegram group .


    Learn more