<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/">
    <channel>
        <title>Eloise88</title>
        <link>https://paragraph.com/@eloise88</link>
        <description>undefined</description>
        <lastBuildDate>Wed, 10 Jun 2026 22:14:20 GMT</lastBuildDate>
        <docs>https://validator.w3.org/feed/docs/rss2.html</docs>
        <generator>https://github.com/jpmonette/feed</generator>
        <language>en</language>
        <copyright>All rights reserved</copyright>
        <item>
            <title><![CDATA[Create Your Own Hilarious ChatGPT Bot in Telegram with Python: A Step-by-Step Guide]]></title>
            <link>https://paragraph.com/@eloise88/create-your-own-hilarious-chatgpt-bot-in-telegram-with-python-a-step-by-step-guide</link>
            <guid>9PWMv069ATjIiRtm4brx</guid>
            <pubDate>Wed, 18 Jan 2023 16:37:52 GMT</pubDate>
            <description><![CDATA[Update 16 January: Added /img for AI generated images Ready to bring some much-needed humor to your group chats? This guide shows you how to easily add the hilarious OpenAI ChatGPT bot to any Telegram group with just a few lines of Python code. Whether you’re a coding pro or just starting out, we’ve got you covered with a step-by-step guide. Get ready to revolutionize your chats and have a good laugh! https://t.me/askchatgpt * Feeling daring? Go ahead and skip the step-by-step guide and put i...]]></description>
            <content:encoded><![CDATA[<p><strong><em>Update 16 January: Added /img for AI generated images</em></strong></p><p>Ready to bring some much-needed humor to your group chats? This guide shows you how to easily <strong>add the hilarious OpenAI ChatGPT bot to any Telegram group with just a few lines of Python code</strong>. Whether you’re a coding pro or just starting out, we’ve got you covered with a step-by-step guide. Get ready to revolutionize your chats and have a good laugh!</p><p><a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://t.me/askchatgpt">https://t.me/askchatgpt</a></p><p>* <a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://t.me/askchatgpt">Feeling daring? Go ahead and skip the step-by-step guide and put it to the ultimate test by sending it a message using the link above.</a>*</p><h2 id="h-1-to-begin-ensure-that-python-is-installed" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">1. To begin, ensure that Python is installed</h2><h2 id="h-2-next-obtain-telegram-api-authentication-credentials" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">2. Next obtain Telegram API authentication credentials</h2><p>First things first, you’ll need to <strong>create a new bot and snag its </strong><a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://core.telegram.org/bots/tutorial"><strong>shiny API token</strong></a>. Don’t worry, it’s easy peasy! Just chat with the BotFather bot on Telegram and he’ll walk you through the process. Follow these steps and you’ll be on your way to bot greatness:</p><figure float="none" data-type="figure" class="img-center" style="max-width: null;"><img src="https://storage.googleapis.com/papyrus_images/9f8973c6d70d523ba83d8d8f7dc4b35f914799f6bf5b1bbf2fe638fc062ead2c.png" alt="https://www.sohamkamani.com/nodejs/telegram-bot/" blurdataurl="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACwAAAAAAQABAAACAkQBADs=" nextheight="600" nextwidth="800" class="image-node embed"><figcaption HTMLAttributes="[object Object]" class="">https://www.sohamkamani.com/nodejs/telegram-bot/</figcaption></figure><p>Open a conversation with the <strong>BotFather</strong> bot on Telegram by searching for “@BotFather” in the Telegram search bar. <strong>Type “/newbot”</strong> to create a new bot. Follow the prompts to choose a name and username for your bot. The <strong>username must end in “bot”</strong> (e.g. “my_new_bot”).</p><figure float="none" data-type="figure" class="img-center" style="max-width: null;"><img src="https://storage.googleapis.com/papyrus_images/7b602359042d9a79e21435629595ddaa14af845ba36b099beb74628aa4c0d7e2.png" alt="https://core.telegram.org/bots/tutorial" blurdataurl="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACwAAAAAAQABAAACAkQBADs=" nextheight="600" nextwidth="800" class="image-node embed"><figcaption HTMLAttributes="[object Object]" class="">https://core.telegram.org/bots/tutorial</figcaption></figure><p>Once the bot has been created, the BotFather will provide you with a token. <strong>This token is used to authenticate your bot and grant it access to the Telegram API.</strong> Copy the token and use it in your bot’s code to authenticate and access the API. Protect your bot’s secret token like it’s the crown jewels! Do not share your bot’s token with anyone.</p><p>You will then need to <strong>retrieve the chat ID</strong> of the channel you just created on Telegram. This ID is a unique identifier and is used when one wants to integrate Telegram with their own apps or services.</p><figure float="none" data-type="figure" class="img-center" style="max-width: null;"><img src="https://storage.googleapis.com/papyrus_images/5c4d80c625f2e0bd3197b6705550bbfc6d483a84eb19c69d0b4c503d99b8d876.png" alt="https://t.me/ask_chatgptbot" blurdataurl="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACwAAAAAAQABAAACAkQBADs=" nextheight="600" nextwidth="800" class="image-node embed"><figcaption HTMLAttributes="[object Object]" class="">https://t.me/ask_chatgptbot</figcaption></figure><figure float="none" data-type="figure" class="img-center" style="max-width: null;"><img src="https://storage.googleapis.com/papyrus_images/a6dd9f5c81ba0b8c161837d2d81a0cd138e3243326a68ea426e8ceb615f1916e.png" alt="https://t.me/ask_chatgptbot" blurdataurl="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACwAAAAAAQABAAACAkQBADs=" nextheight="600" nextwidth="800" class="image-node embed"><figcaption HTMLAttributes="[object Object]" class="">https://t.me/ask_chatgptbot</figcaption></figure><p>Send a message to this channel through the Bot API, using your channel name and access token. <a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://api.telegram.org/bot11234485678:AAElJxyzHCbiiZu7Vb_fGGhmk2tbFVr54n/sendMessage?chat_id=@TestChannel&amp;text=123">https://api.telegram.org/bot11234485678:AAElJxyzHCbiiZu7Vb_fGGhmk2tbFVr54n/sendMessage?chat_id=@TestChannel&amp;text=123</a></p><pre data-type="codeBlock" text="{&quot;ok&quot;:true,
 &quot;result&quot;:{
 &quot;message_id&quot;:191,
 &quot;sender_chat&quot;:{
  &quot;id&quot;:-1001527664788,
  &quot;title&quot;:&quot;Test Channel Name&quot;,
  &quot;username&quot;:&quot;TestChannel&quot;,&quot;type&quot;:&quot;channel&quot;
 },
 &quot;chat&quot;:{
  &quot;id&quot;:-1001527664788,
  &quot;title&quot;:&quot;&quot;,
  &quot;username&quot;:&quot;TestChannel&quot;,&quot;type&quot;:&quot;channel&quot;
  },
 &quot;date&quot;:1670434355,
 &quot;text&quot;:&quot;123&quot;
 }
}
"><code>{<span class="hljs-string">"ok"</span><span class="hljs-symbol">:true</span>,
 <span class="hljs-string">"result"</span><span class="hljs-symbol">:</span>{
 <span class="hljs-string">"message_id"</span><span class="hljs-symbol">:</span><span class="hljs-number">191</span>,
 <span class="hljs-string">"sender_chat"</span><span class="hljs-symbol">:</span>{
  <span class="hljs-string">"id"</span><span class="hljs-symbol">:-</span><span class="hljs-number">1001527664788</span>,
  <span class="hljs-string">"title"</span><span class="hljs-symbol">:<span class="hljs-string">"Test Channel Name"</span></span>,
  <span class="hljs-string">"username"</span><span class="hljs-symbol">:<span class="hljs-string">"TestChannel"</span></span>,<span class="hljs-string">"type"</span><span class="hljs-symbol">:<span class="hljs-string">"channel"</span></span>
 },
 <span class="hljs-string">"chat"</span><span class="hljs-symbol">:</span>{
  <span class="hljs-string">"id"</span><span class="hljs-symbol">:-</span><span class="hljs-number">1001527664788</span>,
  <span class="hljs-string">"title"</span><span class="hljs-symbol">:<span class="hljs-string">""</span></span>,
  <span class="hljs-string">"username"</span><span class="hljs-symbol">:<span class="hljs-string">"TestChannel"</span></span>,<span class="hljs-string">"type"</span><span class="hljs-symbol">:<span class="hljs-string">"channel"</span></span>
  },
 <span class="hljs-string">"date"</span><span class="hljs-symbol">:</span><span class="hljs-number">1670434355</span>,
 <span class="hljs-string">"text"</span><span class="hljs-symbol">:<span class="hljs-string">"123"</span></span>
 }
}
</code></pre><p>You will find the channel id under chat/id.</p><figure float="none" data-type="figure" class="img-center" style="max-width: null;"><img src="https://storage.googleapis.com/papyrus_images/c9acbca63fa3cbe377e01ef8e4f68d4acd4f07b0784a452f20292425a2f71b14.png" alt="Make sure to promote your Bot as an ADMIN" blurdataurl="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACwAAAAAAQABAAACAkQBADs=" nextheight="600" nextwidth="800" class="image-node embed"><figcaption HTMLAttributes="[object Object]" class="">Make sure to promote your Bot as an ADMIN</figcaption></figure><p><strong>It’s important to give your bot admin privileges in order to ensure it can perform all the necessary tasks.</strong> Attention all coders! Those access token IDs might look nice, but they’re just for show. You’ll need your own for your app.</p><h2 id="h-3-time-to-get-your-api-key-and-connect-to-the-openai-engine-no-sweat" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">3. Time to get your api key and connect to the OpenAI engine, no sweat !</h2><p>To obtain an API key from OpenAI, you will need to create an account on the OpenAI website (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://beta.openai.com/">https://beta.openai.com/</a>). Once you have an account, you can access your API keys by going to the “API Keys” tab on the user dashboard.</p><figure float="none" data-type="figure" class="img-center" style="max-width: null;"><img src="https://storage.googleapis.com/papyrus_images/fcb7bf3ccded1c1f453a6eb4ef8410e7a04363a59d88c05d79c82b8e5a834dab.png" alt="https://beta.openai.com/account/api-keys" blurdataurl="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACwAAAAAAQABAAACAkQBADs=" nextheight="600" nextwidth="800" class="image-node embed"><figcaption HTMLAttributes="[object Object]" class="">https://beta.openai.com/account/api-keys</figcaption></figure><p>From there, you can <strong>generate a new key and use it to authenticate your API requests</strong>. It is important to keep your API key secret and secure to protect your account.</p><figure float="none" data-type="figure" class="img-center" style="max-width: null;"><img src="https://storage.googleapis.com/papyrus_images/7400f7adb8958a07113dc7726d411fd31527298d498d26135928c7f7fddc409c.png" alt="https://beta.openai.com/account/usage" blurdataurl="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACwAAAAAAQABAAACAkQBADs=" nextheight="600" nextwidth="800" class="image-node embed"><figcaption HTMLAttributes="[object Object]" class="">https://beta.openai.com/account/usage</figcaption></figure><p>Keep in mind that OpenAI may limits the number of API calls you can make. With a personal account, you are given a grant of $18.00 to use towards API requests. Be sure to review the terms of service and pricing information on the OpenAI website before using the API.</p><h2 id="h-connecting-to-text-davinci-003" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Connecting to Text-davinci-003</h2><figure float="none" data-type="figure" class="img-center" style="max-width: null;"><img src="https://storage.googleapis.com/papyrus_images/e6f24090d257ce4610a8af1a67243c6f51556f7f3bb1f50dff481e7233e8c5cc.png" alt="https://beta.openai.com/docs/models/gpt-3" blurdataurl="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACwAAAAAAQABAAACAkQBADs=" nextheight="600" nextwidth="800" class="image-node embed"><figcaption HTMLAttributes="[object Object]" class="">https://beta.openai.com/docs/models/gpt-3</figcaption></figure><p><strong>Text-davinci-003</strong> is a large language model developed by OpenAI. It is considered one of the most capable language models currently available, due to its ability to generate human-like text and perform a wide range of language tasks. It was trained on a dataset of billions of words, and can <strong>generate text that is coherent and reads like it was written by a human</strong>.</p><p>All right, code warriors! It’s time to get your bot and Telegram group chatting like old friends. With a few easy steps and a dash of Python magic, you’ll be able to connect and deploy your very own ChatGPT bot in your group in no time. Let’s get coding!</p><h2 id="h-4-begin-writing-python-code" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">4. Begin writing Python code</h2><p>To begin, we will import necessary libraries and set the key authentication parameter.</p><pre data-type="codeBlock" text="# 1. Start by importing the necessary libraries and setting up the API clients 
import requests
import json
import os
import threading


# OpenAI secret Key
API_KEY = &apos;xxxxxxxxxxxsecretAPIxxxxxxxxxx&apos;
# Models: text-davinci-003,text-curie-001,text-babbage-001,text-ada-001
MODEL = &apos;text-davinci-003&apos;
# Telegram secret access bot token
BOT_TOKEN = &apos;xxxxxxbotapikeyxxxxx&apos;
# Defining the bot&apos;s personality using adjectives
BOT_PERSONALITY = &apos;Answer in a funny tone, &apos; 
"><code><span class="hljs-comment"># 1. Start by importing the necessary libraries and setting up the API clients </span>
import requests
import json
import os
import threading


<span class="hljs-comment"># OpenAI secret Key</span>
<span class="hljs-attr">API_KEY</span> = <span class="hljs-string">'xxxxxxxxxxxsecretAPIxxxxxxxxxx'</span>
<span class="hljs-comment"># Models: text-davinci-003,text-curie-001,text-babbage-001,text-ada-001</span>
<span class="hljs-attr">MODEL</span> = <span class="hljs-string">'text-davinci-003'</span>
<span class="hljs-comment"># Telegram secret access bot token</span>
<span class="hljs-attr">BOT_TOKEN</span> = <span class="hljs-string">'xxxxxxbotapikeyxxxxx'</span>
<span class="hljs-comment"># Defining the bot's personality using adjectives</span>
<span class="hljs-attr">BOT_PERSONALITY</span> = <span class="hljs-string">'Answer in a funny tone, '</span> 
</code></pre><p>Introducing the <strong>BOT_PERSONALITY parameter</strong> — your ticket to a ChatGPT with character! Use this handy constant to give your bot a specific tone or manner of speaking, like <strong>friendly, professional, or humorous</strong>. By setting the BOT_PERSONALITY parameter, you can customize the way that ChatGPT talks to your users and create a more personalized and engaging experience.</p><pre data-type="codeBlock" text="Here are 15 specific tones that you can use to customize the personality
of ChatGPT:
1. Friendly
2. Professional
3. Humorous
4. Sarcastic
5. Witty
6. Sassy
7. Charming
8. Cheeky
9. Quirky
10. Laid-back
11. Elegant
12. Playful
13. Soothing
14. Intense
15. Passionate
"><code>Here are 15 specific tones that you can use to customize the personality
of ChatGPT:
<span class="hljs-bullet">1.</span> Friendly
<span class="hljs-bullet">2.</span> Professional
<span class="hljs-bullet">3.</span> Humorous
<span class="hljs-bullet">4.</span> Sarcastic
<span class="hljs-bullet">5.</span> Witty
<span class="hljs-bullet">6.</span> Sassy
<span class="hljs-bullet">7.</span> Charming
<span class="hljs-bullet">8.</span> Cheeky
<span class="hljs-bullet">9.</span> Quirky
<span class="hljs-bullet">10.</span> Laid-back
<span class="hljs-bullet">11.</span> Elegant
<span class="hljs-bullet">12.</span> Playful
<span class="hljs-bullet">13.</span> Soothing
<span class="hljs-bullet">14.</span> Intense
<span class="hljs-bullet">15.</span> Passionate
</code></pre><p>Then, <strong>create a function that retrieves a response from the OpenAI chatbot</strong>.</p><pre data-type="codeBlock" text="# 2a. Function that gets the response from OpenAI&apos;s chatbot
def openAI(prompt):
    # Make the request to the OpenAI API
    response = requests.post(
        &apos;https://api.openai.com/v1/completions&apos;,
        headers={&apos;Authorization&apos;: f&apos;Bearer {API_KEY}&apos;},
        json={&apos;model&apos;: MODEL, &apos;prompt&apos;: prompt, &apos;temperature&apos;: 0.4, &apos;max_tokens&apos;: 300}
    )

    result = response.json()
    final_result = &apos;&apos;.join(choice[&apos;text&apos;] for choice in result[&apos;choices&apos;])
    return final_result

# 2b. Function that gets an AI Image from OpenAI
def openAImage(prompt):
    # Make the request to the OpenAI API
    resp = requests.post(
        &apos;https://api.openai.com/v1/images/generations&apos;,
        headers={&apos;Authorization&apos;: f&apos;Bearer {API_KEY}&apos;},
        json={&apos;prompt&apos;: prompt,&apos;n&apos; : 1, &apos;size&apos;: &apos;1024x1024&apos;}
    )
    response_text = json.loads(resp.text)
      
    return response_text[&apos;data&apos;][0][&apos;url&apos;]
"><code># 2a. Function that gets the response <span class="hljs-keyword">from</span> OpenAI<span class="hljs-string">'s chatbot
def openAI(prompt):
    # Make the request to the OpenAI API
    response = requests.post(
        '</span>https:<span class="hljs-comment">//api.openai.com/v1/completions',</span>
        headers<span class="hljs-operator">=</span>{<span class="hljs-string">'Authorization'</span>: f<span class="hljs-string">'Bearer {API_KEY}'</span>},
        json<span class="hljs-operator">=</span>{<span class="hljs-string">'model'</span>: MODEL, <span class="hljs-string">'prompt'</span>: prompt, <span class="hljs-string">'temperature'</span>: <span class="hljs-number">0</span><span class="hljs-number">.4</span>, <span class="hljs-string">'max_tokens'</span>: <span class="hljs-number">300</span>}
    )

    result <span class="hljs-operator">=</span> response.json()
    final_result <span class="hljs-operator">=</span> <span class="hljs-string">''</span>.join(choice[<span class="hljs-string">'text'</span>] <span class="hljs-keyword">for</span> choice in result[<span class="hljs-string">'choices'</span>])
    <span class="hljs-keyword">return</span> final_result

# 2b. Function that gets an AI Image <span class="hljs-keyword">from</span> OpenAI
def openAImage(prompt):
    # Make the request to the OpenAI API
    resp <span class="hljs-operator">=</span> requests.post(
        <span class="hljs-string">'https://api.openai.com/v1/images/generations'</span>,
        headers<span class="hljs-operator">=</span>{<span class="hljs-string">'Authorization'</span>: f<span class="hljs-string">'Bearer {API_KEY}'</span>},
        json<span class="hljs-operator">=</span>{<span class="hljs-string">'prompt'</span>: prompt,<span class="hljs-string">'n'</span> : <span class="hljs-number">1</span>, <span class="hljs-string">'size'</span>: <span class="hljs-string">'1024x1024'</span>}
    )
    response_text <span class="hljs-operator">=</span> json.loads(resp.text)
      
    <span class="hljs-keyword">return</span> response_text[<span class="hljs-string">'data'</span>][<span class="hljs-number">0</span>][<span class="hljs-string">'url'</span>]
</code></pre><figure float="none" data-type="figure" class="img-center" style="max-width: null;"><img src="https://storage.googleapis.com/papyrus_images/6acf1ef157dee964f29635a70e21c03d6901ba60b7d7b45c7de3397c7010ae7b.png" alt="#Example print(openAI(“What is entropy ?”))" blurdataurl="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACwAAAAAAQABAAACAkQBADs=" nextheight="600" nextwidth="800" class="image-node embed"><figcaption HTMLAttributes="[object Object]" class="">#Example print(openAI(“What is entropy ?”))</figcaption></figure><p>This function 2.a will send a <strong>POST request to the OpenAI API with a given input</strong> (like ‘What is entropy?’) for the API to analyze. The temperature parameter controls how random the generated response will be — lower values mean more predictable text. The max_tokens parameter sets a limit on the number of words and punctuation in the response. And presto! The function will return the generated response from the specified OpenAI model.</p><p>Next up, it’s time to <strong>build a function that sends a message to a specific Telegram group.</strong></p><pre data-type="codeBlock" text="# 3a. Function that sends a message to a specific telegram group
def telegram_bot_sendtext(bot_message,chat_id,msg_id):
    data = {
        &apos;chat_id&apos;: chat_id,
        &apos;text&apos;: bot_message,
        &apos;reply_to_message_id&apos;: msg_id
    }
    response = requests.post(
        &apos;https://api.telegram.org/bot&apos; + BOT_TOKEN + &apos;/sendMessage&apos;,
        json=data
    )
    return response.json()

# 3b. Function that sends an image to a specific telegram group
def telegram_bot_sendimage(image_url, group_id, msg_id):
    data = {
        &apos;chat_id&apos;: group_id, 
        &apos;photo&apos;: image_url,
        &apos;reply_to_message_id&apos;: msg_id
    }
    url = &apos;https://api.telegram.org/bot&apos; + BOT_TOKEN + &apos;/sendPhoto&apos;
    
    response = requests.post(url, data=data)
    return response.json()
"><code># 3a. Function that sends a message to a specific telegram group
def telegram_bot_sendtext(bot_message,chat_id,msg_id):
    data <span class="hljs-operator">=</span> {
        <span class="hljs-string">'chat_id'</span>: chat_id,
        <span class="hljs-string">'text'</span>: bot_message,
        <span class="hljs-string">'reply_to_message_id'</span>: msg_id
    }
    response <span class="hljs-operator">=</span> requests.post(
        <span class="hljs-string">'https://api.telegram.org/bot'</span> <span class="hljs-operator">+</span> BOT_TOKEN <span class="hljs-operator">+</span> <span class="hljs-string">'/sendMessage'</span>,
        json<span class="hljs-operator">=</span>data
    )
    <span class="hljs-keyword">return</span> response.json()

# 3b. Function that sends an image to a specific telegram group
def telegram_bot_sendimage(image_url, group_id, msg_id):
    data <span class="hljs-operator">=</span> {
        <span class="hljs-string">'chat_id'</span>: group_id, 
        <span class="hljs-string">'photo'</span>: image_url,
        <span class="hljs-string">'reply_to_message_id'</span>: msg_id
    }
    url <span class="hljs-operator">=</span> <span class="hljs-string">'https://api.telegram.org/bot'</span> <span class="hljs-operator">+</span> BOT_TOKEN <span class="hljs-operator">+</span> <span class="hljs-string">'/sendPhoto'</span>
    
    response <span class="hljs-operator">=</span> requests.post(url, data<span class="hljs-operator">=</span>data)
    <span class="hljs-keyword">return</span> response.json()
</code></pre><p>The above 3.a sends a message to a specific Telegram group through the use of the Telegram API. The function takes three arguments: <code>bot_message</code>which is the message to be sent, <code>chat_id</code>which is the unique identifier of the chat where the message will be sent, and <code>msg_id</code> which specifies the unique identifier of the message that you want to reply to. The function uses the requests library to send a GET request to the Telegram API with the necessary parameters, including the API key, chat ID, and message to be sent.</p><p>Now it’s time to get to the good stuff — building a function that retrieves the <strong>latest requests</strong> from users in a Telegram group, generates a clever <strong>response using OpenAI</strong>, and <strong>sends it back to the group</strong>. Let’s do this thing!</p><pre data-type="codeBlock" text="# 4. Function that retrieves the latest requests from users in a Telegram group, 
# generates a response using OpenAI, and sends the response back to the group.

def Chatbot():
    # Retrieve last ID message from text file for ChatGPT update
    cwd = os.getcwd()
    filename = cwd + &apos;/chatgpt.txt&apos;
    if not os.path.exists(filename):
        with open(filename, &quot;w&quot;) as f:
            f.write(&quot;1&quot;)
    else:
        print(&quot;File Exists&quot;)    

    with open(filename) as f:
        last_update = f.read()
        
    # Check for new messages in Telegram group
    url = f&apos;https://api.telegram.org/bot{BOT_TOKEN}/getUpdates?offset={last_update}&apos;
    response = requests.get(url)
    data = json.loads(response.content)
        
    for result in data[&apos;result&apos;]:
        try:
            # Checking for new message
            if float(result[&apos;update_id&apos;]) &gt; float(last_update):
                # Checking for new messages that did not come from chatGPT
                if not result[&apos;message&apos;][&apos;from&apos;][&apos;is_bot&apos;]:
                    last_update = str(int(result[&apos;update_id&apos;]))
                    
                    # Retrieving message ID of the sender of the request
                    msg_id = str(int(result[&apos;message&apos;][&apos;message_id&apos;]))
                    
                    # Retrieving the chat ID 
                    chat_id = str(result[&apos;message&apos;][&apos;chat&apos;][&apos;id&apos;])

                    # Checking if user wants an image
                    if &apos;/img&apos; in result[&apos;message&apos;][&apos;text&apos;]:
                        prompt = result[&apos;message&apos;][&apos;text&apos;].replace(&quot;/img&quot;, &quot;&quot;)
                        bot_response = openAImage(prompt)
                        print(telegram_bot_sendimage(bot_response, chat_id, msg_id))

                    # Checking that user mentionned chatbot&apos;s username in message
                    if &apos;@ask_chatgptbot&apos; in result[&apos;message&apos;][&apos;text&apos;]:
                        prompt = result[&apos;message&apos;][&apos;text&apos;].replace(&quot;@ask_chatgptbot&quot;, &quot;&quot;)
                        # Calling OpenAI API using the bot&apos;s personality
                        bot_response = openAI(f&quot;{BOT_PERSONALITY}{prompt}&quot;)
                        # Sending back response to telegram group
                        print(telegram_bot_sendtext(bot_response, chat_id, msg_id))
                    # Verifying that the user is responding to the ChatGPT bot
                    if &apos;reply_to_message&apos; in result[&apos;message&apos;]:
                        if result[&apos;message&apos;][&apos;reply_to_message&apos;][&apos;from&apos;][&apos;is_bot&apos;]:
                            prompt = result[&apos;message&apos;][&apos;text&apos;]
                            bot_response = openAI(f&quot;{BOT_PERSONALITY}{prompt}&quot;)
                            print(telegram_bot_sendtext(bot_response, chat_id, msg_id))
        except Exception as e: 
            print(e)

    # Updating file with last update ID
    with open(filename, &apos;w&apos;) as f:
        f.write(last_update)
    
    return &quot;done&quot;
"><code><span class="hljs-comment"># 4. Function that retrieves the latest requests from users in a Telegram group, </span>
<span class="hljs-comment"># generates a response using OpenAI, and sends the response back to the group.</span>

<span class="hljs-keyword">def</span> <span class="hljs-title function_">Chatbot</span>():
    <span class="hljs-comment"># Retrieve last ID message from text file for ChatGPT update</span>
    cwd = os.getcwd()
    filename = cwd + <span class="hljs-string">'/chatgpt.txt'</span>
    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> os.path.exists(filename):
        <span class="hljs-keyword">with</span> <span class="hljs-built_in">open</span>(filename, <span class="hljs-string">"w"</span>) <span class="hljs-keyword">as</span> f:
            f.write(<span class="hljs-string">"1"</span>)
    <span class="hljs-keyword">else</span>:
        <span class="hljs-built_in">print</span>(<span class="hljs-string">"File Exists"</span>)    

    <span class="hljs-keyword">with</span> <span class="hljs-built_in">open</span>(filename) <span class="hljs-keyword">as</span> f:
        last_update = f.read()
        
    <span class="hljs-comment"># Check for new messages in Telegram group</span>
    url = <span class="hljs-string">f'https://api.telegram.org/bot<span class="hljs-subst">{BOT_TOKEN}</span>/getUpdates?offset=<span class="hljs-subst">{last_update}</span>'</span>
    response = requests.get(url)
    data = json.loads(response.content)
        
    <span class="hljs-keyword">for</span> result <span class="hljs-keyword">in</span> data[<span class="hljs-string">'result'</span>]:
        <span class="hljs-keyword">try</span>:
            <span class="hljs-comment"># Checking for new message</span>
            <span class="hljs-keyword">if</span> <span class="hljs-built_in">float</span>(result[<span class="hljs-string">'update_id'</span>]) > <span class="hljs-built_in">float</span>(last_update):
                <span class="hljs-comment"># Checking for new messages that did not come from chatGPT</span>
                <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> result[<span class="hljs-string">'message'</span>][<span class="hljs-string">'from'</span>][<span class="hljs-string">'is_bot'</span>]:
                    last_update = <span class="hljs-built_in">str</span>(<span class="hljs-built_in">int</span>(result[<span class="hljs-string">'update_id'</span>]))
                    
                    <span class="hljs-comment"># Retrieving message ID of the sender of the request</span>
                    msg_id = <span class="hljs-built_in">str</span>(<span class="hljs-built_in">int</span>(result[<span class="hljs-string">'message'</span>][<span class="hljs-string">'message_id'</span>]))
                    
                    <span class="hljs-comment"># Retrieving the chat ID </span>
                    chat_id = <span class="hljs-built_in">str</span>(result[<span class="hljs-string">'message'</span>][<span class="hljs-string">'chat'</span>][<span class="hljs-string">'id'</span>])

                    <span class="hljs-comment"># Checking if user wants an image</span>
                    <span class="hljs-keyword">if</span> <span class="hljs-string">'/img'</span> <span class="hljs-keyword">in</span> result[<span class="hljs-string">'message'</span>][<span class="hljs-string">'text'</span>]:
                        prompt = result[<span class="hljs-string">'message'</span>][<span class="hljs-string">'text'</span>].replace(<span class="hljs-string">"/img"</span>, <span class="hljs-string">""</span>)
                        bot_response = openAImage(prompt)
                        <span class="hljs-built_in">print</span>(telegram_bot_sendimage(bot_response, chat_id, msg_id))

                    <span class="hljs-comment"># Checking that user mentionned chatbot's username in message</span>
                    <span class="hljs-keyword">if</span> <span class="hljs-string">'@ask_chatgptbot'</span> <span class="hljs-keyword">in</span> result[<span class="hljs-string">'message'</span>][<span class="hljs-string">'text'</span>]:
                        prompt = result[<span class="hljs-string">'message'</span>][<span class="hljs-string">'text'</span>].replace(<span class="hljs-string">"@ask_chatgptbot"</span>, <span class="hljs-string">""</span>)
                        <span class="hljs-comment"># Calling OpenAI API using the bot's personality</span>
                        bot_response = openAI(<span class="hljs-string">f"<span class="hljs-subst">{BOT_PERSONALITY}</span><span class="hljs-subst">{prompt}</span>"</span>)
                        <span class="hljs-comment"># Sending back response to telegram group</span>
                        <span class="hljs-built_in">print</span>(telegram_bot_sendtext(bot_response, chat_id, msg_id))
                    <span class="hljs-comment"># Verifying that the user is responding to the ChatGPT bot</span>
                    <span class="hljs-keyword">if</span> <span class="hljs-string">'reply_to_message'</span> <span class="hljs-keyword">in</span> result[<span class="hljs-string">'message'</span>]:
                        <span class="hljs-keyword">if</span> result[<span class="hljs-string">'message'</span>][<span class="hljs-string">'reply_to_message'</span>][<span class="hljs-string">'from'</span>][<span class="hljs-string">'is_bot'</span>]:
                            prompt = result[<span class="hljs-string">'message'</span>][<span class="hljs-string">'text'</span>]
                            bot_response = openAI(<span class="hljs-string">f"<span class="hljs-subst">{BOT_PERSONALITY}</span><span class="hljs-subst">{prompt}</span>"</span>)
                            <span class="hljs-built_in">print</span>(telegram_bot_sendtext(bot_response, chat_id, msg_id))
        <span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> e: 
            <span class="hljs-built_in">print</span>(e)

    <span class="hljs-comment"># Updating file with last update ID</span>
    <span class="hljs-keyword">with</span> <span class="hljs-built_in">open</span>(filename, <span class="hljs-string">'w'</span>) <span class="hljs-keyword">as</span> f:
        f.write(last_update)
    
    <span class="hljs-keyword">return</span> <span class="hljs-string">"done"</span>
</code></pre><p>But wait, there’s more! We’ll also make sure they’re from a real user (not a pesky bot), and sends them to the OpenAI API for analysis if they mention the bot’s username and are a reply to the bot.</p><p>Okay, final step! It’s time to add a scheduling component to your bot so it can regularly check for new messages in the group and send responses as needed. Python’s threading library can help you out with this.</p><pre data-type="codeBlock" text="# 5 Running a check every 5 seconds to check for new messages
def main():
    timertime=5
    Chatbot()
   
    # 5 sec timer
    threading.Timer(timertime, main).start()

# Run the main function
if __name__ == &quot;__main__&quot;:
    main()
"><code><span class="hljs-comment"># 5 Running a check every 5 seconds to check for new messages</span>
def main():
    <span class="hljs-attr">timertime</span>=<span class="hljs-number">5</span>
    Chatbot()
   
    <span class="hljs-comment"># 5 sec timer</span>
    threading.Timer(timertime, main).start()

<span class="hljs-comment"># Run the main function</span>
if <span class="hljs-attr">__name__</span> == <span class="hljs-string">"__main__"</span>:
    main()
</code></pre><p>Ta-da! Presenting the fruits of your labor: the final Python code for your fancy new chatbot. Just copy and paste this bad boy into your favorite code editor, plug in your API keys and chat group ID, and you’ll be chatting it up with ChatGPT in no time.</p><p><strong>Full overview of the code (</strong><a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://raw.githubusercontent.com/Eloise1988/OPENAI/main/robot.py"><strong>github link here</strong></a><strong>):</strong></p><p><a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://raw.githubusercontent.com/Eloise1988/OPENAI/main/robot.py">https://raw.githubusercontent.com/Eloise1988/OPENAI/main/robot.py</a></p><p>And there you have it, folks! With a few simple steps and a bit of Python magic, <strong>you’ve successfully created a chatbot for your Telegram group using OpenAI. Congratulations!</strong> Time to sit back and watch the hilarious responses roll in. Or, you know, do some fine-tuning and customization to make your chatbot truly unique. Either way, the world (or at least your group chat) is now your chatbot-filled oyster.</p><figure float="none" data-type="figure" class="img-center" style="max-width: null;"><img src="https://storage.googleapis.com/papyrus_images/d14628685d92abe42dceb1bcef913e0cb2f38eedbe127759c92bfe32cbb68669.gif" alt="Testing it out at https://t.me/askchatgpt" blurdataurl="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACwAAAAAAQABAAACAkQBADs=" nextheight="600" nextwidth="800" class="image-node embed"><figcaption HTMLAttributes="[object Object]" class="">Testing it out at https://t.me/askchatgpt</figcaption></figure><p>L<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://t.me/askchatgpt">et the chatbot shenanigans begin!</a> Simply click on the link below and send a message to @ask_chatGPTbot</p>]]></content:encoded>
            <author>eloise88@newsletter.paragraph.com (Eloise88)</author>
            <enclosure url="https://storage.googleapis.com/papyrus_images/4eccee049187da9e941e78b2c19ce10d60b888156e025c3817b61e2b6eb0f30d.jpg" length="0" type="image/jpg"/>
        </item>
    </channel>
</rss>