Add files via upload

This commit is contained in:
Muhammad Herdy Iskandar
2023-06-28 13:42:33 +07:00
committed by GitHub
parent 7a68ed95f0
commit 7d296eca0a
5 changed files with 157 additions and 0 deletions

80
README.md Normal file
View File

@@ -0,0 +1,80 @@
<p align="center">
<a href="https:t.me/EndayWithGPTBot"><img alt="Avatar Bot Image" src="images/avatarbot.png" width="250px" /> </a>
<h1 align="center">EndayWithOpenAI</h1>
</p>
# Introduction
This project is created to fulfill one of the requirements for the selection stage of OPREC LAB SEIC ITPLN 👨🏻‍💻 ⚡
Firstly, I would like to express my sincere gratitude to all my friends who have provided support and offered constructive criticism and suggestions.
In this project, I implemented Chat OpenAI with a Telegram bot. The main objective of this project is to create a bot that can communicate with users through messages and provide responses based on user requests.
At the beginning of the source code, several modules and libraries are imported such as ```os```, ```openai```, ```dotenv```, ```aiogram```, and ```keep_alive```. Then, environment variables are retrieved using the ```os.getenv()``` method, and the Telegram bot token is stored in the ```tgBot_token``` variable. The OpenAI API key is also retrieved and stored in the ```openAi_token``` variable.
Next, message handlers are defined using the ```dp.message_handler()``` decorator. There are message handlers for the ```/start```, ```/command```, ```/help```, and ```/stop``` commands. The ```welcome``` function is used to provide a welcome message to the user and introduce the purpose of this project. The ```left``` function provides a list of available commands. The ```documentation``` function gives instructions and tactics for getting better responses. The ```gpt``` function is the default message handler used to send the user's prompt to the OpenAI model and generate a response that is sent back to the user.
At the end of the source code, the ```keep_alive()``` function is called to keep the bot active, and the program starts monitoring incoming messages using the ```executor.start_polling(dp)``` method.
Thus, this source code allows the development of a Telegram bot that uses the OpenAI GPT model to engage in conversations with users.
# How To Install
### Prerequisites
- Python 3.7. or higher. <a href="https://www.python.org/downloads" target="_blank"><strong>Download Here</strong></a>
- Install Modul/Framework/Library
```
pip install os
```
```
pip install openai
```
```
pip install python-dotenv
```
```
pip install aiogram
```
and this optional :
```
pip install keep_alive
```
### Clone The Repository
1. Open a terminal (Command Prompt on Windows or Terminal on macOS/Linux).
2. Navigate to the directory where you want to save the cloned repository (e.g., cd /path/to/folder).
3. Type the git clone command followed by the copied repository URL
4. Copy this : and press Enter.
```sh
git clone https://github.com/dyzulk/chatbot-telegram-with-openai.git
```
5. Wait for a moment until the cloning process is complete. Once finished, you will have a local copy of the repository in the specified directory.
6. By following these steps, you have successfully cloned the project from the GitHub repository to your local machine.
### Or Download This Repo
<a href="https://github.com/dyzulk/chatbot-telegram-with-openai/archive/refs/heads/main.zip" target="_blank"><strong>Click Here To Download</strong></a>
### Change The API Token
```sh
tgBot_token=API_TOKEN_BOT
openAi_token=API_TOKEN_OPENAI
```
To replace them with valid API tokens, you need to obtain the tokens from the respective services. For example, if you want to use the Telegram Bot API token, you need to register your bot with BotFather and obtain a valid bot token from there. Similarly, if you want to use the OpenAI API token, you need to have an OpenAI account and obtain a valid API token from your account's settings panel.
Once you have the valid tokens, replace "API_TOKEN_BOT" with the provided Telegram bot token and replace "API_TOKEN_OPENAI" with the provided OpenAI token. Make sure to remove the double quotation marks around the tokens to ensure they are recognized as valid strings in the code.
By making these replacements, you will set the values of the tgBot_token and openAi_token variables according to the required API tokens for your application.
# Support Us
You can support me on the SociaBuzz platform! Your support would be greatly appreciated, but even starring this project would be really helpful!
<a href="https://sociabuzz.com/dyzulkdeveloper/support" target="_blank"><strong>Support Here</strong></a>

Binary file not shown.

BIN
images/avatarbot.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 96 KiB

15
keep_alive.py Normal file
View File

@@ -0,0 +1,15 @@
from flask import Flask,render_template
from threading import Thread
app = Flask(__name__)
@app.route('/')
def index():
return "Alive"
def run():
app.run(host='0.0.0.0',port=8080)
def keep_alive():
t = Thread(target=run)
t.start()

62
main.py Normal file
View File

@@ -0,0 +1,62 @@
import os
import openai
from dotenv import load_dotenv
from aiogram import Bot, Dispatcher, executor, types
# from keep_alive import keep_alive
load_dotenv()
bot = Bot(token=os.getenv("tgBot_token"))
dp = Dispatcher(bot)
openai.api_key = os.getenv("openAi_token")
@dp.message_handler(commands=['start'])
async def welcome(message: types.Message):
await message.reply(
"Halo! Saya Enday With GPT chat bot. Tanyakan saya sesuatu 😊"
)
await message.reply(
"Project ini dibuat untuk menuntaskan salah satu persyaratan dari tahapan seleksi OPREC LAB SEIC ITPLN 👨🏻‍💻 ⚡"
)
await message.reply(
"- Catatan :\n\nEndayWithGPT memiliki pengetahuan terbatas tentang dunia dan peristiwa mulai dari Tahun 2021 M ke belakang hingga seterusnya.\n\n-----------------------------------\n\"/command\" untuk mengetahui perintah yang ada.\n\"/help\" Dapatkan sedikit bantuan.\n\n\nAtau lebih lengkapnya baca panduan berikut : t.me/NdayWithGPT"
)
@dp.message_handler(commands=['command'])
async def left(message: types.Message):
await message.reply("\"/start\" memulai aktivitas bot\n\"/command\" untuk mengetahui perintah yang ada.\n\"/help\" Dapatkan sedikit bantuan\n\"/stop\" meberhentikan aktivitas bot")
@dp.message_handler(commands=['help'])
async def documentation(message: types.Message):
await message.reply(
"** TULIS INSTRUKSI YANG JELAS\n\nGPT tidak dapat membaca pikiran Anda. Jika hasilnya terlalu panjang, mintalah balasan singkat. Jika hasilnya terlalu sederhana, mintalah tulisan tingkat ahli. Jika Anda tidak menyukai formatnya, tunjukkan format yang ingin Anda lihat. Semakin sedikit GPT yang harus menebak apa yang Anda inginkan, semakin besar kemungkinan Anda mendapatkannya.\n\n* Contoh :\n=> Ringkas teks yang dibatasi oleh tanda kutip tiga dengan haiku. \"\"\"masukkan teks di sini\"\"\""
)
await message.reply(
"** TAKTIK: SERTAKAN DETAIL DALAM KUERI ANDA UNTUK MENDAPATKAN JAWABAN YANG LEBIH RELEVAN\n\nUntuk mendapatkan respons yang sangat relevan, pastikan permintaan memberikan detail atau konteks penting. Kalau tidak, Anda menyerahkannya kepada model untuk menebak apa yang Anda maksud.\n\n* Contoh Lebih Buruk\n=> Siapa presiden?\n\n* Contoh Lebih Baik\n=> Siapa presiden Indonesia pada tahun 2023, dan seberapa sering pemilu diadakan?"
)
await message.reply(
"** TAKTIK: GUNAKAN PEMBATAS UNTUK MENUNJUKKAN DENGAN JELAS BAGIAN INPUT YANG BERBEDA\n\nPembatas seperti tanda kutip tiga, tag XML, judul bagian, dll. Dapat membantu membatasi bagian teks agar diperlakukan berbeda."
)
await message.reply(
"** TAKTIK: TENTUKAN PANJANG OUTPUT YANG DIINGINKAN\n\nAnda dapat meminta model untuk menghasilkan output dengan panjang target tertentu. Panjang keluaran yang ditargetkan dapat ditentukan dalam hal jumlah kata, kalimat, paragraf, poin-poin, dll. Namun perlu dicatat bahwa menginstruksikan model untuk menghasilkan sejumlah kata tertentu tidak bekerja dengan presisi tinggi. Model dapat lebih andal menghasilkan keluaran dengan jumlah paragraf atau poin-poin tertentu.\n\n* Contoh :\n=> Ringkas teks yang dibatasi oleh tanda kutip tiga dalam sekitar 50 kata. \"\"\"masukkan teks di sini\"\"\"\n\n=> Ringkas teks yang dibatasi oleh tanda kutip tiga dalam 2 paragraf. \"\"\"masukkan teks di sini\"\"\""
)
@dp.message_handler(commands=['stop'])
async def left(message: types.Message):
await message.reply("Sampai Jumpa!\nTerimakasih Telah Berkunjung 😊")
@dp.message_handler()
async def gpt(message: types.Message):
response = openai.Completion.create(model="text-davinci-003",
prompt=message.text,
temperature=0.5,
max_tokens=924,
top_p=1,
frequency_penalty=0.0,
presence_penalty=0.0)
await message.reply(response.choices[0].text)
# keep_alive()
if __name__ == "__main__":
executor.start_polling(dp)