How to set webhook telegram bot


php - How to set Telegram bot webhook?

Asked

Modified 2 months ago

Viewed 42k times

I'm developing a Telegram bot, and I want to set the webhook to my domain's URL. I've already generated a self-signed certificate following the Telegram's guide. However, I'm not able to set the webhook. I've searched previous answers and found this one, but it doesn't work to me. Can anybody explain me how to upload the SSL certificate and set the webhook?

  • php
  • ssl
  • telegram
  • webhooks
  • telegram-bot
https://api.telegram.org/bot{my_bot_token}/setWebhook?url={url_to_send_updates_to} 

For instance:

https://api.telegram.org/bot123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11/setWebhook?url=https://www. example.com 
https://api.telegram.org/bot{my_bot_token}/setWebhook?url= 

response:

{"ok":true,"result":true,"description":"Webhook was deleted"} 
https://api.telegram.org/bot{my_bot_token}/getWebhookInfo 

I created a file on my server for conveniently setting up telegram webhooks.

You can use the same file on your server.

This should be on the same server from which you wish to run the Telegram Bot

<html> <head> <title>Set Webhooks</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.6.0/css/bulma.min.css" /> <script src="https://unpkg.com/vue/dist/vue.js"></script> </head> <body> <div> <div> <form :action="set_webhook" method="post" enctype="multipart/form-data"> <label>Enter your Token</label> <p> <input type="text" v-model="token" /> </p> <label>Enter your Host</label> <p> <input type="text" v-model="host" /> </p> <label>Enter your Port</label> <p> <input type="text" v-model="port" /> </p> <input type="hidden" name="url" v-model="bot_url"> <label>Maximum Connections?</label> <p> <input type="text" name="max_connections" value="100" /> </p> <br/> <p>{{ bot_url }}</p> <br/> <label>Enter your Certificate</label> <p> <input type="file" name="certificate" /> </p> <br/> <div> <p> <button name="submit">Set Webhook</button> </p> <br/> <p> <a :href="get_webhook_info" target="_blank">Get Webhook Info</a> </p> </div> </div> </div> <script> new Vue({ el: '#app', data: { token: 'xxx', port: 88, host: 'your-server. com', }, computed: { get_webhook_info: function () { return 'https://api.telegram.org/bot' + this.token + '/getwebhookinfo' }, set_webhook: function () { return 'https://api.telegram.org/bot' + this.token + '/setwebhook' }, bot_url: function () { return 'https://' + this.host + ':' + this.port + '/' + this.token } } } ) </script> </body> </html> 
  1. Drop this file on the same server you wish to host you bots
  2. Ensure the mime-type for .pem is enabled on your webserver
  3. Browse to this page on our server
  4. Fill the form with your BOT_TOKEN and chosen PORT
  5. Upload your certificate file
  6. Submit the form

You will get a successful result:

{"ok":true,"result":true,"description":"Webhook was set"} 

2

this is the correct one

<html> <head> <title>Set Webhooks</title> <link rel="stylesheet" href="https://cdnjs. cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.6.0/css/bulma.min.css" /> <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script> </head> <body> <div> <div> <form :action="set_webhook" method="post" enctype="multipart/form-data"> <label>Enter your Token</label> <p> <input type="text" v-model="token" /> </p> <label>Enter your Host</label> <p> <input type="text" v-model="host" /> </p> <label>Enter your Port</label> <p> <input type="text" v-model="port" /> </p> <input type="hidden" name="url" v-model="bot_url"> <label>Maximum Connections?</label> <p> <input type="text" name="max_connections" value="100" /> </p> <br/> <p>{{ bot_url }}</p> <br/> <label>Enter your Certificate</label> <p> <input type="file" name="certificate" /> </p> <br/> <div> <p> <button name="submit">Set Webhook</button> </p> <br/> <p> <a :href="get_webhook_info" target="_blank">Get Webhook Info</a> </p> </div> </div> </div> <script> const { createApp } = Vue Vue. createApp({ el: '#app', data() { return { token: 'xxx', port: 88, host: 'your-server.com', } }, computed: { get_webhook_info: function () { return 'https://api.telegram.org/bot' + this.token + '/getwebhookinfo' }, set_webhook: function () { return 'https://api.telegram.org/bot' + this.token + '/setwebhook' }, bot_url: function () { return 'https://' + this.host + ':' + this.port + '/' + this.token } } } ).mount('#app') </script> </body> </html>

1

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

flask - How to set webhook for telegram bot in python?

Asked

Modified 1 year, 10 months ago

Viewed 2k times

I've created a bot and it works fine with heroku. I wanted to use webhooks to handle messages but i can't understand how to do it. Here's what i did:

  1. Uploaded this code to heroku

telegrampiu24.py

import telepot import json from flask import Flask, request, abort from telepot.namedtuple import * bot = telepot.Bot("123456789:abcdefghijklmnopqrstuvwxyz") app = Flask(__name__) @app.route('/', methods=['POST','GET']) def webhook(): if request.method == 'POST': print("post") return Response('post',status=200) else: print("get") return Response('get',status=200) if __name__ == '__main__' or __name__ == '__telegrampiu24__': app.run() 
  1. Set the webhook with https://api.telegram.org/bot123456789:abcdefghijklmnopqrstuvwxyz/setwebhook?url=https://provaxyz1.herokuapp.com/ (obviously with my correct token)

I'm stuck here since if i send a message to my bot and see the logs on heroku i always get errors

2021-02-26T13:12:24. 889213+00:00 app[test.1]: * Serving Flask app "telegrampiu24" (lazy loading) 2021-02-26T13:12:24.889246+00:00 app[test.1]: * Environment: production 2021-02-26T13:12:24.889247+00:00 app[test.1]: WARNING: This is a development server. Do not use it in a production deployment. 2021-02-26T13:12:24.889247+00:00 app[test.1]: Use a production WSGI server instead. 2021-02-26T13:12:24.889290+00:00 app[test.1]: * Debug mode: off 2021-02-26T13:12:24.891889+00:00 app[test.1]: * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) 2021-02-26T13:12:26.000000+00:00 app[api]: Build succeeded 2021-02-26T13:13:02.086234+00:00 heroku[router]: at=error code=h24 desc="No web processes running" method=POST path="/" host=provaxyz1.herokuapp.com request_id=54bdbd45bdf fwd="IP" dyno= connect= service= status=503 bytes= protocol=https 

I don't get what I'm doing wrong, any help is very appreciated! Thanks in advance

  • python
  • flask
  • heroku
  • bots
  • telegram

2

See, the document on The Procfile:

A Heroku app’s web process type is special: it’s the only process type that can receive external HTTP traffic from Heroku’s routers. If your app includes a web server, you should declare it as your app’s web process.

With this in mind, your error: No web processes running suggests you should change your Procfile to contain:

web: python "telegrampiu24.py" 

This issue woudln't have happened before, as prior to putting webhook support in your bot, it didn't need to receive HTTP traffic because the other method uses 'polling' where the process connects to telegram's servers as a client.

Although be aware that this is still Flask's dev server. You should look to deploy with a production WSGI server like gunicorn in the long run. Add gunicorn to your requirements.txt and then have the Procfile:

web: gunicorn telegrampiu24:app 

1

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

Telegram Webhook - what is it and how to set up

Telegram is a popular instant messenger for communicating via text and voice messages. The developers have provided several interesting technologies.

Therefore, today we will talk about what Telegram Webhook is. Also in the process of narration, we will consider the features of the functionality, as well as the scope, configuration methods.

Content

  1. What is Telegram Webhook
  2. How to register a bot for Webhook
  3. Launch problems
  4. Results

What is Telegram Webhook

Webhook is a technology that allows you to track events in the messenger in real time. The main advantage of this approach is the delivery of data to the specified address via the eSputnik system.

This allows information to be collected and delivered without direct operator response.

This technology is best implemented in the work of bots. There are several types of them: gaming, assistants, chat bots and informants. nine0003

The interaction itself is organized as follows:

  1. The user writes a command to the chat with the program code.
  2. Built-in algorithms accept the request and send it to the project servers.
  3. The command is processed and sent back in a form understandable to the user.
  4. The algorithm displays information on the display.

This sequence of actions works the same for almost any interaction with bots. And Webhook technology simplifies this process and ensures the stability of ongoing processes. nine0003

If everything is clear with this, then let's talk about how to register a bot with this technology.

How to register a Webhook bot

The procedure for connecting a Webhook bot is somewhat different from creating a simple automated algorithm - it is based on the use of a self-signed certificate.

To implement our plans:

  1. Install the openSSI package.
  2. Generating the correct access key and self-signed certificate. nine0012
  3. Enter the server address in the empty field for entering "Common Name".
  4. Open the certificate directory and create two parameters bot. py and config.py.
  5. Click on the second object and create a bot token variable.
  6. Importing a couple of libraries for the bot.py parameter.
  7. Creating a server.
  8. We send a self-signed certificate to it, prescribe the return path for information.
  9. Change the system settings if necessary and start the server. nine0012
  10. Go to the application and look for the Telegram setWebhook bot.
  11. We activate the input line and send several messages.
  12. If the status code in the opened window is 200, then the built-in algorithms are working normally.

As soon as you see the value of this status code, you can consider the procedure successfully completed.

If everything is clear with this so far, let's talk about possible problems when running a bot on Webhook.

Starting problems

There are a lot of messages on the Web that the prescribed algorithm stops working after a while or immediately after launch. To avoid this, here are some simple tips:

  1. Type the @Botfather command. It will help the code to get rid of problems and errors in the code. If everything is really bad, a corrected copy of the bot will be automatically created.
  2. Activate the chat with the /setprivacy command. After specifying the address of your algorithms, the program will publish a list of errors and give recommendations on how to fix them. nine0012
  3. If the chat is not working, but the bot is working normally, please contact technical support for clarification.
  4. If the assistant is completely broken and does not work, open the source code and check it for errors.

With these simple steps, you can increase the chances of restarting the bot, and also not bring the situation to the level of "catastrophic". The help of built-in algorithms and technical support specialists will help in solving most problems.

Results

Telegram Webhook is a useful technology for automating the process of communication with users. As a rule, this functionality is implemented in bots so as not to waste time sending, receiving and processing responses.

Interaction with the system is represented by the link: telegram-bot-server-processing-bot-chat in Telegram. In this way, you can organize communication in a fully automated way, and distract only occasionally.

The procedure for attaching a bot to a Telegram has a few special features in the form of creating an additional certificate that is used to connect the server with the bot. nine0003

If you are having problems with the bot, check the source code for errors or contact technical support for help.

The article provides comprehensive information on the topic, so you, dear friends, have to use the acquired knowledge in practice. Try it and you will succeed!

Lesson 4: Webhooks | Writing bots for Telegram in Python The first of these, and perhaps the most important, is webhooks. nine0003

What is the real difference?

(The next paragraph was written in 2015-2016, the libraries have been updated a lot since then, so in some cases using Long Polling will be no worse than webhooks) .
Let's first understand how bots receive messages. The first and simplest option is to periodically poll the Telegram servers for new information. All this is carried out through the so-called. Long polling, i.e. a connection is opened for a short time and all updates immediately arrive to the bot. Simple, but not very reliable. Firstly, Telegram servers periodically start returning a 504 (Gateway Timeout) error, which is why some bots fall into a stupor. Even the pyTelegramBotAPI I use can't always survive this. Secondly, if several bots are running at the same time, the likelihood of encountering errors increases. This is doubly disappointing if the bots themselves are not used very often. nine0003

Webhooks work a little differently. When you install a webhook, you kind of say to the Telegram servers: “Listen, if someone writes to me, knock here - (link)”. There is no need to periodically poll the servers yourself, thereby eliminating the unpleasant cause of bot crashes. However, you have to pay for this by the need to install a full-fledged web server on the machine on which you plan to run bots. What is more unpleasant, you need to have your own SSL certificate, because. Telegram webhooks only work over HTTPS. Fortunately, one day, support for self-signed certificates appeared. Here I will talk about their application. nine0003

Create a certificate

I repeat: I don't consider myself a super-mega-cool IT specialist, maybe I'm doing something wrong, nevertheless, it works and looks pretty decent. Okay, let's get started.
First, install the openssl package (for Linux):
sudo apt-get install openssl
Then generate a private key:
openssl genrsa -out webhook_pkey.pem 2048
team:
openssl req -new -x509 -days 3650 -key webhook_pkey.pem -out webhook_cert.pem
We will be prompted to enter some information about ourselves: a two-letter country code, organization name, etc. If you do not want to enter anything, put a period. BUT! IMPORTANT! When you get to the prompt to enter the Common Name, you should write the IP address of the server on which the bot will be launched.

Certificate generation

As a result, we get files webhook_cert.pem and webhook_pkey.pem , put them in some empty directory, in which we will later create a bot. Certificates are ready, now let's deal with the bot. In order not to overload our brains too much, let's write a simple echo-bot from lesson #1, only now using a certificate.

Our cherry server

Above, I mentioned the need for a web server to work with webhooks. Those who are proficient in Apache or Nginx can read no further. Personally, I could not (and still cannot) figure out how to process incoming messages from these servers in Python. Therefore, a simple and quite effective solution was made - we use the CherryPy web framework. This is not the easiest framework compared to, for example, Flask, but we will use it. nine0117 So let's install CherryPy with a simple command python3 -m pip install cherrypy

New old bot

Let's go to the directory with our certificates and create files bot. py and config.py . In the latter, we will create a variable token , into which we will pass the token of our bot. Open bot.py .
Import 2 libraries, set the necessary constants and create a bot instance:

 import telebot import cherrypy import config WEBHOOK_HOST = 'IP address of the server running the bot' WEBHOOK_PORT = 443 # 443, 80, 88 or 8443 (port must be open!) WEBHOOK_LISTEN = '0.0.0.0' # Some servers will require the same IP as above WEBHOOK_SSL_CERT = './webhook_cert.pem' # Path to certificate WEBHOOK_SSL_PRIV = './webhook_pkey.pem' # Path to private key WEBHOOK_URL_BASE = "https://%s:%s" % (WEBHOOK_HOST, WEBHOOK_PORT) WEBHOOK_URL_PATH = "/%s/" % (config.token) bot = telebot.TeleBot(config.token) nine0173 

Note that Telegram only supports 4 different ports when working with self-signed certificates. Theoretically, this means that no more than 4 webhook bots can be launched on one machine. In practice, this is fixable, but more on that next time.

Let's create a class that implements a web server instance. This is, in principle, a standard code that will not change much from bot to bot:

 # Our webhook server class WebhookServer(object): @cherrypy.expose def index(self): if 'content-length' in cherrypy.request.headers and \ 'content-type' in cherrypy.request.headers and \ cherrypy.request.headers['content-type'] == 'application/json': length = int(cherrypy.request.headers['content-length']) json_string = cherrypy.request.body.read(length).decode("utf-8") update = telebot.types.Update.de_json(json_string) # This function provides validation of the incoming message bot.process_new_updates([update]) return '' else: raise cherrypy.HTTPError(403) nine0173 

Look at the name of the function: index . This essentially means the last part of the URL. Let me explain with an example: if we wanted to receive updates to the address 80.100.95.20/webhooksbot , then we would call the function above webhooksbot . index is analogous to not having any additional routing. Why change this value to another, is described here 12, now it is not needed.
So what do we see in the code above? We accept incoming requests at URL our.ip.address/ , get the content and run it through the set of handlers. By the way, about them. Because we implement the simplest echo-bot, we need only one handler:

 # Handler for all text messages @bot.message_handler(func=lambda message: True, content_types=['text']) def echo_message(message): bot.reply_to(message, message.text) 

An attentive reader will still notice one difference, which I won't talk about ;) At the same time, one more reason to open the documentation.

Next, send our self-signed certificate and a “return address” to the server to which we ask to report all new messages:

 # Remove webhook before reinstalling (saves some problems) bot. remove_webhook() # Reinstall the webhook bot.set_webhook(url=WEBHOOK_URL_BASE + WEBHOOK_URL_PATH, certificate=open(WEBHOOK_SSL_CERT, 'r')) 

Finally, let's set up our server and start it up!

 # Specify CherryPy server settings cherrypy.config.update({ 'server.socket_host': WEBHOOK_LISTEN, 'server.socket_port': WEBHOOK_PORT, 'server.ssl_module': 'builtin', 'server.ssl_certificate': WEBHOOK_SSL_CERT, 'server.ssl_private_key': WEBHOOK_SSL_PRIV }) # Actually, launch! cherrypy.quickstart(WebhookServer(), WEBHOOK_URL_PATH, {'/': {}}) nine0173 

Pay attention to the last line. Our server as a “root” will listen to an address of the form “ip-address/bot_token”, relative to which index is this address. Maybe I explained it a little crookedly, but later everything will become extremely clear to you, now you don’t need to clutter your head with unnecessary information.

Let's start the bot and write a couple of messages to it.


Learn more