Coder Social home page Coder Social logo

ifsvivek / localbot Goto Github PK

View Code? Open in Web Editor NEW
6.0 3.0 0.0 764 KB

Local Bot is a fun and interactive bot built using Python's Discord library. It provides various commands and features to enhance the user experience within Discord servers.

Home Page: http://gh.ifsvivek.tech/LocalBot/

License: MIT License

Python 80.21% HTML 19.79%
discord discord-bot py-cord

localbot's Introduction

Description

This Discord bot is a fun and interactive bot that provides various commands to users within a Discord server. It includes features such as ping testing, cat and dog images, dice rolling, number guessing game, coin flipping, chatting with the bot, and generating images based on prompts.

Installation

  1. Clone or download the repository to your local machine.
  2. Install the required dependencies by running pip install -r requirements.txt.
  3. Create a .env file in the root directory of the project.
  4. Inside the .env file, add your Discord bot token in the following format:
    TOKEN=your_discord_bot_token_here
    GENIUS_TOKEN=your_genius_token_here
    API_KEY=your_openwebui_token_here
    SERVER_URL=your_openwebui_server_url_here
    MODEL=model_name_here
    
  5. Ensure your bot has the necessary permissions in your Discord server.
  6. Run the bot script by executing python LocalBot.py or python LocalBot_phone.py in your terminal, depending on your use case.
  7. or use nohup python3 LocalBot.py & to run the bot in the background.

Usage

Once the bot is running and connected to your Discord server, users can interact with it using various commands prefixed with $. The bot supports both traditional commands and slash commands for enhanced interaction within Discord.

Available Commands

Command Description Options/Notes
/cat or $cat Sends a random cat image.
/dog or $dog Sends a random dog image.
/gtn or $gtn Starts a number guessing game.
/hello or $hello Greets the user.
/dice [sides] or $dice [sides] Rolls a dice with the specified number of sides. Default is 6 sides if none specified.
/flip or $flip Flips a coin.
/ask or $ask Provides a yes/no response randomly.
/chat [message] or $chat [message] Engages in a chat with the bot using the text-generation model.
$imagine [prompt] Generates an image based on the provided prompt. --magic: Uses a magic prompt.
--model: Specify the model to use for image generation. Range: [0, 1, 2, 3, 4,5].
/purge [amount] or $purge [amount] Deletes the specified number of messages in the channel. Requires the Manage Messages permission.
$clear [amount] Clears the specified number of messages in the DM.
/join or Joins the voice channel of the user.
/leave or Leaves the voice channel.
/play [song] or Plays the specified song in the voice channel.
/stop or Stops the currently playing song.
/lyrics Fetches the lyrics of the specified song.

Contributing

Contributions to the project are welcome. If you have any suggestions, bug fixes, or additional features you'd like to implement, feel free to fork the repository, make your changes, and submit a pull request.

Dependencies

  • discord.py: For creating and managing the Discord bot.
  • python-dotenv: For managing environment variables.
  • requests: For making HTTP requests (used in some commands for fetching data).
  • py-cord: For supporting slash commands.
  • transformers: For text-generation capabilities in chat interactions.
  • lyricsgenius : For fetching song lyrics.
  • youtube_dl: For playing music in voice channels.
  • ffmpeg: For audio processing in voice channels.
  • Pillow: For image processing and generation.

License

This project is licensed under the MIT License - see the LICENSE file for details.

localbot's People

Contributors

dorikyh avatar ifsvivek avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

localbot's Issues

Issue with Synchronous Functions in Asynchronous Environment

Issue with Synchronous Functions in Asynchronous Environment

I've noticed that the project is using synchronous functions in several parts of the code. This is problematic because Pycord is an asynchronous library, and using synchronous functions can cause blocking and slowdowns in the bot. This includes using the requests module.

Example

def ollama_chat(prompt, model, system_prompt):
    # Combine the system prompt with the user's prompt
    complete_prompt = system_prompt + "\n" + prompt
    payload = {"prompt": complete_prompt, "model": model, "max_tokens": 150}
    response = requests.post(OLLAMA_API_URL, json=payload)
    response.raise_for_status()
    parts = response.text.strip().split("\n")
    combined_response = ""
    for part in parts:
        json_part = json.loads(part)
        combined_response += json_part.get("response", "")
    return combined_response

Problems in this code

  1. Synchronous Function Declaration: Declaring the function as synchronous causes the entire program to stop just to execute that function. Since the bot is constantly executing different functions simultaneously, this can lead to significant slowdowns. To avoid this, the function should be defined as asynchronous and called with await.
  2. You are using requests, this is a synchronous module so every request will stop your bot completely until the requests is finished, the same thing I said in the first point.

Suggestions to fix the example

import aiohttp
import asyncio
import json

async def ollama_chat(prompt, model, system_prompt):
    # Combine the system prompt with the user's prompt
    complete_prompt = system_prompt + "\n" + prompt
    payload = {"prompt": complete_prompt, "model": model, "max_tokens": 150}
    
    async with aiohttp.ClientSession() as session:
        async with session.post(OLLAMA_API_URL, json=payload) as response:
            response.raise_for_status()
            text = await response.text()
            parts = text.strip().split("\n")
            combined_response = ""
            for part in parts:
                json_part = json.loads(part)
                combined_response += json_part.get("response", "")
            return combined_response

Now this function works asynchronously, so you have to call it in this way: await ollama_chat(). This way, the function won't block your bot, allowing many users to execute it and get a response without causing the bot to slow down or shut down.

I also recommend using await ctx.defer() in commands that take a long time to respond. If an interaction (user executing the command) takes more than 5 seconds to respond, it will return Unknown interaction to the user. Using defer, the bot will respond with Bot is thinking, giving it time to execute the command.

In addition, you should completely eliminate the requests module and non-asynchronous functions from the project, and implement asynchronous solutions.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.