This repository contains a simple Discord bot written in Python. The bot listens for messages in a Discord server and responds based on predefined responses. It can also handle private messages.
- Responds to user messages with predefined replies.
- Can distinguish between public and private messages.
- Simple command set including greeting, providing sample Python code, and rolling a dice.
- Python 3.12.4 .
- A Discord account & a bot token.
-
Clone the repository:
git clone https://github.com/youssefjabri/Discord-Bot-Python.git cd Discord-Bot-Python -
Install the required packages:
pip install -r requirements.txt
-
Set up your
.envfile:Create a
.envfile in the root directory of the project and add your Discord bot token:DISCORD_TOKEN=your_discord_bot_token_here
-
Run the bot:
python main.py
-
Interact with the bot:
- Send a message containing "hello" and the bot will respond with "Hello there!"
- Ask for a simple Python code snippet with "give me a simple code with python" and the bot will provide a basic example.
- Request a dice roll with "roll dice" and the bot will simulate rolling a dice.
- The bot will respond with a generic message if it doesn't understand the input.
main.py: Main script that sets up the Discord bot and handles message events.Responses.py: Contains logic for generating responses based on user messages.requirements.txt: Lists the dependencies required for the project..env: File containing environment variables, specifically the Discord bot token.
This script initializes and runs the Discord bot. It contains the following main sections:
-
Load environment variables from
.envfile:load_dotenv() TOKEN: Final[str] = os.getenv('DISCORD_TOKEN')
-
Configure Discord intents and create the client:
intents: Intents = Intents.default() intents.message_content = True client: Client = Client(intents=intents)
-
Function to send messages in response to users:
async def send_message(message: Message, user_message: str) -> None:
-
Event triggered when the bot is ready:
@client.event async def on_ready() -> None:
-
Event triggered with each new message:
@client.event async def on_message(message: Message) -> None:
-
Run the bot:
def main() -> None: client.run(TOKEN) if __name__ == '__main__': main()
This script contains the get_response function which processes user input and returns appropriate responses.
from random import choice, randint def get_response(user_input: str) -> str: lowered: str = user_input.lower() if lowered == '': return "Well you're awfully silent" elif 'hello' in lowered: return 'Hello there!' elif 'give me a simple code with python' in lowered: return '`print("Hello World!")`' elif 'roll dice' in lowered: return f'You rolled: {randint(1, 6)}' else: return choice([ "I don't understand", "What are you talking about?", ])Lists the dependencies required for the project:
python-dotenv discord Stores the Discord bot token:
DISCORD_TOKEN=your_discord_bot_token_here