AiBot(Created by Ujjwal)

Ai Chat bot, Coded by @CoderBoi_Ujjwal
mail@pastecode.io avatar
unknown
python
7 months ago
2.6 kB
5
Indexable
Never
import os
import json
import asyncio
from pyrogram import Client, filters, idle
from pyrogram.types import Message
import openai
from openai import api_key as API_KEY  

CREDENTIALS_FILE = "credentials.txt"

async def install_packages():
    pkgs = ["pyrogram==2.0.106", "TgCrypto", "openai"]
    print("Installing necessary packages", end="\r")
    for pkg in pkgs:
        os.system(f"pip install {pkg}")
    print("Installation Completed")

async def load_credentials():
    if os.path.exists(CREDENTIALS_FILE):
        with open(CREDENTIALS_FILE, "r") as file:
            credentials = json.load(file)
            API_KEY = credentials.get("api_key", "")
            BOT_TOKEN = credentials.get("bot_token", "")
            API_HASH = credentials.get("api_hash", "")
            API_ID = credentials.get("api_id", "")
    else:
        API_KEY = input("Enter your OpenAI API Key: ")
        BOT_TOKEN = input("Enter BOT Token: ")
        API_HASH = input("Enter Api hash: ")
        API_ID = input("Enter your Api id: ")

        credentials = {
            "api_key": API_KEY,
            "bot_token": BOT_TOKEN,
            "api_hash": API_HASH,
            "api_id": API_ID
        }

        with open(CREDENTIALS_FILE, "w") as file:
            json.dump(credentials, file)

    return API_KEY, BOT_TOKEN, API_HASH, API_ID

async def start_bot():
    print("Starting bot")

    API_KEY, BOT_TOKEN, API_HASH, API_ID = await load_credentials()

    AiBot = Client("AiBot", api_id=API_ID, api_hash=API_HASH, bot_token=BOT_TOKEN, in_memory=True)

    @AiBot.on_message(filters.command("start"))
    async def start_command(_, message: Message):
        await message.reply_text("Hello! I am your AI bot. Send me any text, and I'll try to respond intelligently using OpenAI's GPT-3.")

    @AiBot.on_message(filters.text)
    async def reply_to_text(_, message: Message):
        txt = message.text
        resp = await gen_resp(txt)   
        await message.reply_text(resp)

    async def gen_resp(input):
        prompt = f"User: {input}\nBot:"
        response = openai.Completion.create(
            engine="text-davinci-003",
            prompt=prompt,
            temperature=0.5,
            max_tokens=1000,
            top_p=1,
            frequency_penalty=0.1,
            presence_penalty=0.0,
        )
        return response.choices[0].text.strip()

    AiBot.start()
    print(f"{AiBot.get_me().username} Started Successfully\n\n Coded by :- @CoderBoi_Ujjwal")
    idle()

if __name__ == "__main__":
    asyncio.run(install_packages())
    asyncio.run(start_bot())
Leave a Comment