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中文網其他相關文章!