在discord.py中使用Gmail API每分钟以单独消息的形式发送最近10封未读的电子邮件,可以按照以下步骤进行操作:
pip install discord.py google-api-python-client google-auth-httplib2 google-auth-oauthlib
credentials.json
。import discord
import os
import pickle
import base64
import json
import google.auth
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient.discovery import build
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']
TOKEN_PICKLE = 'token.pickle'
EMAIL_COUNT = 10
def get_gmail_service():
creds = None
if os.path.exists(TOKEN_PICKLE):
with open(TOKEN_PICKLE, 'rb') as token:
creds = pickle.load(token)
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
with open(TOKEN_PICKLE, 'wb') as token:
pickle.dump(creds, token)
service = build('gmail', 'v1', credentials=creds)
return service
def get_unread_emails(service):
results = service.users().messages().list(userId='me', labelIds=['INBOX', 'UNREAD'], maxResults=EMAIL_COUNT).execute()
messages = results.get('messages', [])
return messages
def get_email_content(service, message_id):
message = service.users().messages().get(userId='me', id=message_id).execute()
return message['snippet']
on_ready
事件中初始化Gmail服务,并在每分钟的循环中获取未读邮件并发送到discord聊天中:@client.event
async def on_ready():
print('Bot is ready.')
service = get_gmail_service()
while True:
messages = get_unread_emails(service)
for message in messages:
content = get_email_content(service, message['id'])
await client.send_message(discord.Object(id='YOUR_CHANNEL_ID'), content)
await asyncio.sleep(60) # 每分钟循环一次
请确保将YOUR_CHANNEL_ID
替换为你要发送邮件的discord频道的ID。
client.run('YOUR_DISCORD_BOT_TOKEN')
请确保将YOUR_DISCORD_BOT_TOKEN
替换为你的discord机器人应用程序的令牌。
这样,你的discord.py机器人应用程序就会每分钟发送最近10封未读的电子邮件到指定的discord频道中。
领取专属 10元无门槛券
手把手带您无忧上云