Discord Bot with Twitch API Integration

This configuration combines a Discord bot using discord.py with a Flask server to handle incoming HTTP requests from the Twitch API. The goal is to trigger actions in the Discord bot based on Twitch events, like notifying a channel when a streamer goes live.

Required Libraries

Make sure to install the necessary libraries:

pip install discord.py Flask

Code Example

Here's a sample implementation:

import discord
import asyncio
from flask import Flask, request

# Initialize Flask app
app = Flask(__name__)

@app.route('/posts', methods=['POST'])
def handle_twitch_event():
    # Extract data from the incoming request
    event_data = request.json
    # Example: Notify a Discord channel when a streamer goes live
    if event_data['event']['type'] == 'stream.online':
        channel = discord.utils.get(client.get_all_channels(), name='your-channel-name')
        asyncio.run(channel.send(f"{event_data['event']['user_name']} is now live!"))
    return 'Event received', 200

# Initialize Discord client
client = discord.Client()

@client.event
async def on_ready():
    print(f'Logged in as {client.user.name} (ID: {client.user.id}')

@client.event
async def on_message(message):
    if message.author == client.user:
        return
    # Example command handling
    if message.content.startswith('!hello'):
        await message.channel.send('Hello!')

# Run Flask in a separate thread
if __name__ == '__main__':
    from threading import Thread
    Thread(target=lambda: app.run(port=5000)).start()
    client.run('YOUR_DISCORD_BOT_TOKEN')

Explanation

  • Flask Server: The Flask app listens for POST requests at the /posts endpoint. When a Twitch event is received, it checks the event type and sends a message to a specified Discord channel.
  • Discord Bot: The Discord bot connects to the Discord API and can respond to messages and commands.
  • Threading: The Flask server runs in a separate thread, allowing the Discord bot to operate concurrently.

Notes

  • Replace 'your-channel-name' with the actual name of your Discord channel.
  • Ensure that your Twitch API is set up to send events to your Flask server's URL.