Friday, April 19, 2024
HomeGolangThe best way to construct a Telegram Bot

The best way to construct a Telegram Bot


On this tutorial, you’ll learn to simply talk between your bot and your Golang program.

Objectives

Your bot will deal with two use circumstances:

  • Dictionary: you ship a phrase and the bot reply with totally different meanings based mostly on the a part of speech classification of the phrase
  • Writer Data: reply to writer info request

Create the bot inside Telegram

The very first thing it’s best to do is create the bot inside your Telegram account. To do that you’ll need to go looking in your telegram by a chat name BotFather, and ship a message to them /newbot, after selecting a reputation to your bot after which you’ll obtain a token. This token is essential, it’s like a password to manage your bot.

On the lookout for a Golang Job? Examine the Golang Jobs Board

First steps with Golang and Telegram

Telegram has servers, these servers work as a middleware between the chats and the appliance, it’s like a submit workplace however as an alternative of a postal code right here you could have a chat_id. In one other future tutorial, I can go extra deeply into this, nevertheless it’s the one factor you have to know now.

You need to create a handler to your bot as a result of he must know the way ought to reply to one thing. So, we’ll construct a struct to cope with the requests from the telegram and the handler.

Right here you possibly can look and see the opposite fields embrace in a request: https://core.telegram.org/bots/api#replace

import requests, uvicorn, json
from fastapi import FastAPI, Type, Response
from twilio.twiml.messaging_response import MessagingResponse
  

bot_app = FastAPI()

def formatOutput(Physique, information):
    
    if 'error' not in information:
        data_output = json.dumps(information['nutritions'])
        data_output = data_output.substitute(" ", "") #take away whitespaces
    else:
        data_output = json.dumps(information)
        data_output = data_output.substitute(":", "n") #create paragraphs

    data_output = data_output.substitute('"', '') #get solely the vitamin info
    data_output = data_output.substitute(",", "n") #create paragraphs
    data_output = data_output.substitute("{","").substitute("}", "") #take away brackets
    
    data_output = Physique +"n n" + data_output #add the header

    return data_output


def getInfoFruit(fruit_name):

    fruit_name = fruit_name.decrease()
    url="https://fruityvice.com/api/fruit/{}".format(fruit_name)
    resp = requests.get(url)
    if resp.status_code != 200:
        return {"error": "not a fruit"}
    information = resp.json()
    
    return information 

@bot_app.submit("/bot")
async def chat(Physique: str = Type(...)):
   
    information = getInfoFruit(Physique)
    output = formatOutput(Physique, information)
    response = MessagingResponse()
    msg = response.message(output)

    return Response(content material=str(response), media_type="utility/xml")


if __name__ == "__main__":
    uvicorn.run(bot_app, host="0.0.0.0", port=5000)

It’s a must to change “YOUR_TOKEN” to the token that BotFather gives you, so “bot” + YOUR_TOKEN.

However… what is going to he do?

It’s easy to grasp, that each time the handler is triggered, this implies, when you ship a message inside a chat together with your Bot (sure, it’s best to open a chat with the bot you create) — he’ll reply you: Hiya World.

Deploy your Golang “Hiya World” Telegram Bot

I’ve to present many due to the writer of https://www.sohamkamani.com/golang/telegram-bot/ for this tutorial as a result of helped me so much to grasp how can we construct a bot and deploy it.

  1. Set up ngrok from right here https://ngrok.com/obtain
  2. After putting in, you run in your terminal:
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments