DEV Community

Cover image for Simple Discord Bot That Fetches Data (BS4)
Michael
Michael

Posted on

7 2 1 2 2

Simple Discord Bot That Fetches Data (BS4)

This is a straightforward tutorial that utilizes BS4 to retrieve data from an API and subsequently showcases the fetched information on a Discord server.

To create a Discord bot that fetches information from a website and displays it, you can use a programming language like Python and a library like Discord.py. Here are the basic steps to create the bot:

1. Create a project folder and create a Python virtual environment for it. Install Discord.py library and other dependencies like requests, bs4 (BeautifulSoup).

2. Create a Discord bot and get its token from Discord Developer dashboard. You can follow the official documentation to create and invite a bot into a Discord server.

3. Use the requests library to fetch the HTML content of the targeted website. Use BeautifulSoup to parse the HTML content and extract the required information. Store the extracted information in a variable.

4. Use the Discord.py library to define and run a Command that responds to user input. Use the extracted information as the response from the bot. The response can include text and/or images.

5. Test the bot by running it in the terminal. Use the bot token to connect it to a Discord server and test its functionality.

Here is a sample code to fetch daily weather information for a city using OpenWeatherMap API:

import requests
from bs4 import BeautifulSoup
import os
import discord
from dotenv import load_dotenv

load_dotenv()

client = discord.Client()
WEATHER_API_KEY = os.getenv("WEATHER_API_KEY")


@client.event
async def on_ready():
    print(f{client.user} has connected to Discord!')


@client.event
async def on_message(message):
    if message.content.startswith('!weather'):
        city = message.content.split("!weather ", 1)[1]

        url = f'https://api.openweathermap.org/data/2.5/weather?q={city}&appid={WEATHER_API_KEY}&units=metric'

        response = requests.get(url)
        data = response.json()

        description = data['weather'][0]['description']
        temp = data['main']['temp']
        humidity = data['main']['humidity']

        response_text = f"The weather in {city} is {description}. The temperature is {temp}°C and the humidity is {humidity}%."

        await message.channel.send(response_text)


client.run(os.getenv("DISCORD_TOKEN"))
Enter fullscreen mode Exit fullscreen mode

This code fetches the weather data from OpenWeatherMap API and sends it as a response to the user's message command. The data is displayed in the Discord server channel where the user invoked the command. You can modify this code to fetch and display information from any other website or API.

My intention was to create a user-friendly solution for those who are new to Discord and APIs, and hence, I aimed at keeping it 'simple'. Building the bot through the developer portal involves several intricate steps, which I wanted to avoid.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (2)

Collapse
 
vaulterco profile image
vaulterco

Awesome, thank you!

Collapse
 
kitcoder profile image
Michael

Of course, going to post many more and create a collection :)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs