Unsplash 上 Daniel Tafjord 的封面照片
我最近完成了一个软件工程训练营,开始研究 LeetCode 的简单问题,并觉得如果我每天都有解决问题的提醒,这将有助于让我负责。我决定使用按 24 小时计划运行的不和谐机器人(当然是在我值得信赖的树莓派上)来实现此操作,该机器人将执行以下操作:
我意识到每天去 LeetCode 解决一个问题可能会更容易,但在 ChatGPT 的这个迷你项目的帮助下,我学到了很多关于 Python 和 Discord 的知识。这也是我第一次尝试写草图,请多多包涵哈哈
1.使用python虚拟环境
2.安装依赖
3. 建立Leetcode易题数据库
4.设置环境变量
5. 创建 Discord 应用
6. 运行机器人!
我建议使用Python虚拟环境,因为当我最初在Ubuntu 24.04上测试它时,遇到了以下错误
设置相对简单,只需运行以下命令,瞧,你就进入了 python 虚拟环境!
python3 -m venv ~/py_envs ls ~/py_envs # to confirm the environment was created source ~/py_envs/bin/activate
需要以下依赖项:
通过运行以下命令安装 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 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
Leetscrape 对于这一步至关重要。要了解更多信息,请参阅 Leetscrape 文档。
我只想解决 leetcode 简单的问题(对我来说,它们甚至相当困难),所以我做了以下操作:
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")
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)
创建.env文件来存储环境变量
DISCORD_BOT_TOKEN=*****
按照 Discord 开发人员文档中的说明创建具有足够权限的 Discord 应用程序和机器人。请确保至少为机器人授权以下 OAuth 权限:
下面是可以使用 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中文网其他相关文章!