Site icon Full-Stack

Working with APIs like OpenAI or Telegram using Python [2025 Guide]

Application programming interfaces, or APIs, are now a necessary component of any developer’s toolkit. Python makes working with APIs incredibly easy and powerful, whether you’re using OpenAI to generate content or Telegram to send automated messages.

In this blog, we’ll demonstrate how to use Python to integrate with the Telegram Bot API and OpenAI’s API. This post contains everything you need to automate a chatbot or create an AI-powered assistant.

What You’ll Learn:

What is an API?

Your app can communicate with another app or service over an API. Consider it as a bridge that connects your code to OpenAI or Telegram. The majority of APIs return data in JSON format and employ HTTP requests.

Prerequisites

Before we begin, ensure you have the following:

Install required libraries:

pip install requests

Part 1: Create a Telegram Bot

  1. Go to @BotFather on Telegram and create a new bot.
  2. Save the token it provides — you’ll need it for your code.

Python Script to Send Messages:

import requests

TOKEN = 'YOUR_TELEGRAM_BOT_TOKEN'
CHAT_ID = 'YOUR_CHAT_ID'
MESSAGE = 'Hello from my Python bot!'

url = f"https://api.telegram.org/bot{TOKEN}/sendMessage"
payload = {
    "chat_id": CHAT_ID,
    "text": MESSAGE
}

response = requests.post(url, data=payload)
print(response.json())

You can get your chat ID by sending a message to your bot and visiting:
https://api.telegram.org/bot<YOUR_TOKEN>/getUpdates


Part 2: Connect to OpenAI API

Get your API key from OpenAI Dashboard.

Python Script to Generate a Response:

import openai

openai.api_key = "YOUR_OPENAI_API_KEY"

response = openai.ChatCompletion.create(
    model="gpt-3.5-turbo",
    messages=[
        {"role": "user", "content": "Write a short poem about Python."}
    ]
)

print(response.choices[0].message['content'])

Combine Telegram and OpenAI: A Simple Chatbot

Let’s connect everything together. When a user sends a message on Telegram, your bot will use OpenAI to generate a response and send it back.

import requests
import openai
import time

TELEGRAM_TOKEN = 'YOUR_TELEGRAM_BOT_TOKEN'
OPENAI_KEY = 'YOUR_OPENAI_API_KEY'
URL = f"https://api.telegram.org/bot{TELEGRAM_TOKEN}/"

openai.api_key = OPENAI_KEY

def get_updates(offset=None):
    response = requests.get(URL + "getUpdates", params={"offset": offset})
    return response.json()["result"]

def send_message(chat_id, text):
    requests.post(URL + "sendMessage", data={"chat_id": chat_id, "text": text})

def chatgpt_response(prompt):
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages=[{"role": "user", "content": prompt}]
    )
    return response.choices[0].message['content']

def main():
    offset = None
    while True:
        updates = get_updates(offset)
        for update in updates:
            message = update["message"]
            chat_id = message["chat"]["id"]
            text = message.get("text")
            if text:
                reply = chatgpt_response(text)
                send_message(chat_id, reply)
            offset = update["update_id"] + 1
        time.sleep(2)

main()

Bonus: What You Can Build Using These APIs

Final Thoughts

Python makes working with APIs enjoyable and practical. Using Telegram and OpenAI together can help you improve your Python skills, whether you’re communicating with AI or updating users in real time..

You might be like this:-

How to Practice Full Stack Development Skills Daily: A Consistent Path to Mastery

Python Full Stack Developer Salary in Dubai: A Lucrative Career Path

Multithreading in Java: A Practical Guide

Exit mobile version