首页 > 后端开发 > Python教程 > 在 Raspberry Pi 上运行 Discord 机器人

在 Raspberry Pi 上运行 Discord 机器人

Susan Sarandon
发布: 2024-10-01 12:11:02
原创
718 人浏览过

Unsplash 上 Daniel Tafjord 的封面照片

我最近完成了一个软件工程训练营,开始研究 LeetCode 的简单问题,并觉得如果我每天都有解决问题的提醒,这将有助于让我负责。我决定使用按 24 小时计划运行的不和谐机器人(当然是在我值得信赖的树莓派上)来实现此操作,该机器人将执行以下操作:

  • 前往预定义的简单 Leetcode 问题数据库
  • 获取尚未发布到 Discord 频道的问题
  • 将 leetcode 问题作为主题发布到不和谐频道中(这样您就可以轻松添加您的解决方案)
  • 问题被标记为已发布,以避免再次将其发布到频道

Running a Discord Bot on Raspberry Pi

我意识到每天去 LeetCode 解决一个问题可能会更容易,但在 ChatGPT 的这个迷你项目的帮助下,我学到了很多关于 Python 和 Discord 的知识。这也是我第一次尝试写草图,请多多包涵哈哈

Running a Discord Bot on Raspberry Pi

设置

1.使用python虚拟环境
2.安装依赖
3. 建立Leetcode易题数据库
4.设置环境变量
5. 创建 Discord 应用
6. 运行机器人!

1.使用python虚拟环境

我建议使用Python虚拟环境,因为当我最初在Ubuntu 24.04上测试它时,遇到了以下错误

Running a Discord Bot on Raspberry Pi

设置相对简单,只需运行以下命令,瞧,你就进入了 python 虚拟环境!

python3 -m venv ~/py_envs
ls ~/py_envs  # to confirm the environment was created
source ~/py_envs/bin/activate
登录后复制

2.安装依赖

需要以下依赖项:

  • AWS CLI

通过运行以下命令安装 AWS CLI:

curl -O 'https://awscli.amazonaws.com/awscli-exe-linux-aarch64.zip'
unzip awscli-exe-linux-aarch64.zip 
sudo ./aws/install
aws --version
登录后复制

然后运行 ​​aws configure 以添加所需的凭据。请参阅配置 AWS CLI 文档。

  • pip 依赖项

可以通过运行 pip install -rrequirements.txt 来使用需求文件安装以下 pip 依赖项。

# requirements.txt

discord.py
# must install this version of numpy to prevent conflict with
# pandas, both of which are required by leetscrape
numpy==1.26.4   
leetscrape
python-dotenv
登录后复制

3.建立leetcode易题库

Leetscrape 对于这一步至关重要。要了解更多信息,请参阅 Leetscrape 文档。
我只想解决 leetcode 简单的问题(对我来说,它们甚至相当困难),所以我做了以下操作:

  • 使用 leetscrape 从 leetcode 获取所有问题列表并将列表保存到 csv
from leetscrape import GetQuestionsList

ls = GetQuestionsList()
ls.scrape() # Scrape the list of questions
ls.questions.head() # Get the list of questions
ls.to_csv(directory="path/to/csv/file")
登录后复制
  • 创建一个 Amazon DynamoDB 表,并使用从上一步保存的 csv 中筛选出的简单问题列表填充该表。
import csv
import boto3
from botocore.exceptions import BotoCoreError, ClientError

# Initialize the DynamoDB client
dynamodb = boto3.resource('dynamodb')

def filter_and_format_csv_for_dynamodb(input_csv):
    result = []

    with open(input_csv, mode='r') as file:
        csv_reader = csv.DictReader(file)

        for row in csv_reader:
            # Filter based on difficulty and paidOnly fields
            if row['difficulty'] == 'Easy' and row['paidOnly'] == 'False':
                item = {
                    'QID': {'N': str(row['QID'])},  
                    'titleSlug': {'S': row['titleSlug']}, 
                    'topicTags': {'S': row['topicTags']},  
                    'categorySlug': {'S': row['categorySlug']},  
                    'posted': {'BOOL': False}  
                }
                result.append(item)

    return result

def upload_to_dynamodb(items, table_name):
    table = dynamodb.Table(table_name)

    try:
        with table.batch_writer() as batch:
            for item in items:
                batch.put_item(Item={
                    'QID': int(item['QID']['N']),  
                    'titleSlug': item['titleSlug']['S'],
                    'topicTags': item['topicTags']['S'],
                    'categorySlug': item['categorySlug']['S'],
                    'posted': item['posted']['BOOL']
                })
        print(f"Data uploaded successfully to {table_name}")

    except (BotoCoreError, ClientError) as error:
        print(f"Error uploading data to DynamoDB: {error}")

def create_table():
    try:
        table = dynamodb.create_table(
            TableName='leetcode-easy-qs',
            KeySchema=[
                {
                    'AttributeName': 'QID',
                    'KeyType': 'HASH'  # Partition key
                }
            ],
            AttributeDefinitions=[
                {
                    'AttributeName': 'QID',
                    'AttributeType': 'N'  # Number type
                }
            ],
            ProvisionedThroughput={
                'ReadCapacityUnits': 5,
                'WriteCapacityUnits': 5
            }
        )

        # Wait until the table exists
        table.meta.client.get_waiter('table_exists').wait(TableName='leetcode-easy-qs')
        print(f"Table {table.table_name} created successfully!")

    except Exception as e:
        print(f"Error creating table: {e}")

# Call function to create the table
create_table()

# Example usage
input_csv = 'getql.pyquestions.csv'  # Your input CSV file
table_name = 'leetcode-easy-qs'      # DynamoDB table name

# Step 1: Filter and format the CSV data
questions = filter_and_format_csv_for_dynamodb(input_csv)

# Step 2: Upload data to DynamoDB
upload_to_dynamodb(questions, table_name)
登录后复制

4.设置环境变量

创建.env文件来存储环境变量

DISCORD_BOT_TOKEN=*****
登录后复制

5.创建Discord应用程序

按照 Discord 开发人员文档中的说明创建具有足够权限的 Discord 应用程序和机器人。请确保至少为机器人授权以下 OAuth 权限:

  • 发送消息
  • 创建公共线程
  • 在话题中发送消息

6. 运行机器人!

下面是可以使用 python3 Discord-leetcode-qs.py 命令运行的机器人代码。

import os
import discord
import boto3
from leetscrape import GetQuestion
from discord.ext import tasks
from dotenv import load_dotenv
import re
load_dotenv()

# Discord bot token
TOKEN = os.getenv('DISCORD_TOKEN')

# Set the intents for the bot
intents = discord.Intents.default()
intents.message_content = True # Ensure the bot can read messages

# Initialize the bot
bot = discord.Client(intents=intents)
# DynamoDB setup
dynamodb = boto3.client('dynamodb')

TABLE_NAME = 'leetcode-easy-qs'
CHANNEL_ID = 1211111111111111111  # Replace with the actual channel ID

# Function to get the first unposted item from DynamoDB
def get_unposted_item():
    response = dynamodb.scan(
        TableName=TABLE_NAME,
        FilterExpression='posted = :val',
        ExpressionAttributeValues={':val': {'BOOL': False}},
    )
    items = response.get('Items', [])
    if items:
        return items[0]
    return None

# Function to mark the item as posted in DynamoDB
def mark_as_posted(qid):
    dynamodb.update_item(
        TableName=TABLE_NAME,
        Key={'QID': {'N': str(qid)}},
        UpdateExpression='SET posted = :val',
        ExpressionAttributeValues={':val': {'BOOL': True}}
    )

MAX_MESSAGE_LENGTH = 2000
AUTO_ARCHIVE_DURATION = 2880

# Function to split a question into words by spaces or newlines
def split_question(question, max_length):
    parts = []
    while len(question) > max_length:
        split_at = question.rfind(' ', 0, max_length)
        if split_at == -1:
            split_at = question.rfind('\n', 0, max_length)
        if split_at == -1:
            split_at = max_length

        parts.append(question[:split_at].strip())
        # Continue with the remaining text
        question = question[split_at:].strip()

    if question:
        parts.append(question)

    return parts

def clean_question(question):
    first_line, _, remaining_question = message.partition('\n')
    return re.sub(r'\n{3,}', '\n', remaining_question)

def extract_first_line(question):
    lines = question.splitlines()
    return lines[0] if lines else ""

# Task that runs on a schedule
@tasks.loop(minutes=1440) 
async def scheduled_task():
    channel = bot.get_channel(CHANNEL_ID)
    item = get_unposted_item()

    if item:
        title_slug = item['titleSlug']['S']
        qid = item['QID']['N']
        question = "%s" % (GetQuestion(titleSlug=title_slug).scrape())

        first_line = extract_first_line(question)
        cleaned_question = clean_message(question)
        parts = split_message(cleaned_question, MAX_MESSAGE_LENGTH)

        thread = await channel.create_thread(
            name=first_line, 
            type=discord.ChannelType.public_thread
        )

        for part in parts:
            await thread.send(part)

        mark_as_posted(qid)
    else:
        print("No unposted items found.")

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

@bot.event
async def on_thread_create(thread):
    await thread.send("\nYour challenge starts here! Good Luck!")

# Run the bot
bot.run(TOKEN)
登录后复制

运行机器人有多种选项。现在,我只是在 tmux shell 中运行它,但您也可以在 Docker 容器中或在来自 AWS、Azure、DigitalOcean 或其他云提供商的 VPC 上运行它。

现在我只需要尝试解决 Leetcode 问题...

以上是在 Raspberry Pi 上运行 Discord 机器人的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板