de
This commit is contained in:
parent
a93efb4089
commit
4ce6226fcf
1
.env
Normal file
1
.env
Normal file
@ -0,0 +1 @@
|
||||
DISCORD_TOKEN=MTQ4MDkxODI5Mzk5MTc4ODYzNQ.GQ4P7l.uqYM-awr8zAp6eun9iJr0ziDhscv3XiByqSMpw
|
||||
2
.gitignore
vendored
Normal file
2
.gitignore
vendored
Normal file
@ -0,0 +1,2 @@
|
||||
copies.txt
|
||||
|
||||
BIN
__pycache__/weather.cpython-313.pyc
Normal file
BIN
__pycache__/weather.cpython-313.pyc
Normal file
Binary file not shown.
1
calendar/credentials.json
Normal file
1
calendar/credentials.json
Normal file
@ -0,0 +1 @@
|
||||
{"installed":{"client_id":"880804761661-24ss22kt313h0p8godha5po7cmogsdah.apps.googleusercontent.com","project_id":"dask-bot","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://oauth2.googleapis.com/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","client_secret":"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","redirect_uris":["http://localhost"]}}
|
||||
@ -1 +0,0 @@
|
||||
Subproject commit e55b308c1adb705a99bb0b30aa1d6dcc8ce05790
|
||||
83
task_bot.py
83
task_bot.py
@ -11,7 +11,6 @@ global service
|
||||
service = None
|
||||
|
||||
SCOPES = ['https://www.googleapis.com/auth/calendar.readonly']
|
||||
service = None
|
||||
|
||||
load_dotenv()
|
||||
DISCORD_TOKEN = os.getenv("DISCORD_TOKEN")
|
||||
@ -25,45 +24,62 @@ bot = commands.Bot(command_prefix='!', intents=intents)
|
||||
|
||||
|
||||
#Calendar authentification
|
||||
@bot.tree.command()
|
||||
async def authenticate(interaction: discord.Interaction):
|
||||
await interaction.response.defer(thinking=True)
|
||||
async def authenticate():
|
||||
|
||||
print("Authenticating..")
|
||||
global service
|
||||
try:
|
||||
flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file('./calendar/credentials.json', SCOPES)
|
||||
credentials = flow.run_local_server(port=0)
|
||||
service = build('calendar', 'v3', credentials=credentials)
|
||||
await interaction.followup.send('Successfully authenticated with Google Calendar !')
|
||||
except Exception as e:
|
||||
await interaction.followup.send(f'An error occurred: {e}')
|
||||
flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file('./calendar/credentials.json', SCOPES)
|
||||
credentials = flow.run_local_server(port=0)
|
||||
service = build('calendar', 'v3', credentials=credentials)
|
||||
|
||||
|
||||
@bot.tree.command(name='tasks_otd')
|
||||
@bot.tree.command(name='weekly_events')
|
||||
async def events(interaction: discord.Interaction):
|
||||
if service is None:
|
||||
await interaction.response.send_message('Please authenticate first using /authenticate.')
|
||||
return
|
||||
await interaction.response.defer(thinking=True)
|
||||
|
||||
now = datetime.datetime.utcnow()
|
||||
current_weekday = now.weekday()
|
||||
|
||||
now = datetime.datetime.utcnow().isoformat() + 'Z'
|
||||
start_of_day = datetime.datetime.utcnow().replace(hour=0, minute=0, second=0, microsecond=0).isoformat() + 'Z'
|
||||
end_of_day = datetime.datetime.utcnow().replace(hour=23, minute=59, second=59, microsecond=999999).isoformat() + 'Z'
|
||||
start_of_week = now - datetime.timedelta(days=current_weekday)
|
||||
start_of_week = start_of_week.replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
|
||||
events_result = service.events().list(
|
||||
calendarId='primary',
|
||||
timeMin=start_of_day,
|
||||
timeMax=end_of_day,
|
||||
singleEvents=True,
|
||||
orderBy='startTime'
|
||||
).execute()
|
||||
end_of_week = start_of_week + datetime.timedelta(days=6)
|
||||
end_of_week= end_of_week.replace(hour=23, minute=59, second=59, microsecond=999999)
|
||||
|
||||
events = events_result.get('items',[])
|
||||
try:
|
||||
events_result = service.events().list(
|
||||
calendarId='primary',
|
||||
timeMin=start_of_week.isoformat() + 'Z',
|
||||
timeMax=end_of_week.isoformat() + 'Z',
|
||||
singleEvents=True,
|
||||
orderBy='startTime'
|
||||
).execute()
|
||||
|
||||
if not events:
|
||||
await interaction.response.send_message('No tasks for today !')
|
||||
else:
|
||||
tasks = []
|
||||
for event in events:
|
||||
task= f"{event['summary']} at {event['start'].get('dateTime', event['start'].get('date'))}"
|
||||
await interaction.response.send_message('\n'.join(tasks))
|
||||
events = events_result.get('items',[])
|
||||
|
||||
if not events:
|
||||
await interaction.response.send_message('No events this week !')
|
||||
else:
|
||||
embed = discord.Embed(
|
||||
title="📅 Weekly Events Summary",
|
||||
color=discord.Color.blue()
|
||||
)
|
||||
|
||||
for event in events:
|
||||
event_time_str = event['start'].get('dateTime', event['start'].get('date'))
|
||||
if 'Z' in event_time_str:
|
||||
event_time = datetime.datetime.fromisoformat(event_time_str.replace('Z', '+00:00'))
|
||||
else:
|
||||
event_time = datetime.datetime.fromisoformat(event_time_str)
|
||||
|
||||
event_time_local = event_time.strftime("%A, %B %d, %Y, %H:%M")
|
||||
task = f"**{event['summary']}**\n⏰ **At: {event_time_local}**"
|
||||
embed.add_field(name="\u200b", value=task, inline=False)
|
||||
|
||||
await interaction.followup.send(embed=embed)
|
||||
|
||||
except Exception as e:
|
||||
await interaction.followup.send(f'An error occurred: {e}')
|
||||
|
||||
|
||||
#Weather commad tree
|
||||
@ -111,6 +127,7 @@ async def hello_command(interaction: discord.Interaction):
|
||||
@bot.event
|
||||
async def on_ready():
|
||||
print(f'Logged in as {bot.user}')
|
||||
await authenticate()
|
||||
await bot.tree.sync()
|
||||
|
||||
#Liste commandes enregistré
|
||||
|
||||
139
testfile.py
Normal file
139
testfile.py
Normal file
@ -0,0 +1,139 @@
|
||||
import os
|
||||
import discord
|
||||
import datetime
|
||||
import google_auth_oauthlib.flow
|
||||
from weather import OpenWeatherMapAPIClient
|
||||
from googleapiclient.discovery import build
|
||||
from discord.ext import commands
|
||||
from dotenv import load_dotenv
|
||||
|
||||
global service
|
||||
service = None
|
||||
|
||||
SCOPES = ['https://www.googleapis.com/auth/calendar.readonly']
|
||||
service = None
|
||||
|
||||
load_dotenv()
|
||||
DISCORD_TOKEN = os.getenv("DISCORD_TOKEN")
|
||||
WEATHER_TOKEN = os.getenv("WEATHER_TOKEN")
|
||||
|
||||
weather_client = OpenWeatherMapAPIClient(WEATHER_TOKEN, "MyDiscordWeatherBot")
|
||||
intents = discord.Intents(messages=True, guilds=True)
|
||||
intents.message_content = True
|
||||
bot = commands.Bot(command_prefix='!', intents=intents)
|
||||
|
||||
|
||||
|
||||
#Calendar authentification
|
||||
@bot.tree.command()
|
||||
async def authenticate(interaction: discord.Interaction):
|
||||
await interaction.response.defer(thinking=True)
|
||||
global service
|
||||
try:
|
||||
if service:
|
||||
await interaction.response.send_message('Already authenticated with Google Calendar.')
|
||||
return
|
||||
|
||||
flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file('./calendar/credentials.json', SCOPES)
|
||||
credentials = flow.run_local_server(port=0)
|
||||
service = build('calendar', 'v3', credentials=credentials)
|
||||
await interaction.followup.send('Successfully authenticated with Google Calendar !')
|
||||
except Exception as e:
|
||||
await interaction.followup.send(f'An error occurred: {e}')
|
||||
|
||||
|
||||
@bot.tree.command(name='weekly_events')
|
||||
async def events(interaction: discord.Interaction):
|
||||
await interaction.response.defer(thinking=True)
|
||||
|
||||
if service is None:
|
||||
await interaction.followup.send('Please authenticate first using /authenticate.')
|
||||
return
|
||||
|
||||
now = datetime.datetime.utcnow()
|
||||
current_weekday = now.weekday()
|
||||
|
||||
start_of_week = now - datetime.timedelta(days=current_weekday)
|
||||
start_of_week = start_of_week.replace(hour=0, minute=0, second=0, microsecond=0).isoformat() + 'Z'
|
||||
|
||||
end_of_week = start_of_week + datetime.timedelta(days=6)
|
||||
end_of_week= end_of_week.replace(hour=23, minute=59, second=59, microsecond=999999).isoformat() + 'Z'
|
||||
try:
|
||||
events_result = service.events().list(
|
||||
calendarId='primary',
|
||||
timeMin=start_of_week,
|
||||
timeMax=end_of_week,
|
||||
singleEvents=True,
|
||||
orderBy='startTime'
|
||||
).execute()
|
||||
|
||||
events = events_result.get('items',[])
|
||||
|
||||
if not events:
|
||||
await interaction.response.send_message('No tasks for today !')
|
||||
else:
|
||||
tasks = []
|
||||
for event in events:
|
||||
task= f"{event['summary']} at {event['start'].get('dateTime', event['start'].get('date'))}"
|
||||
tasks.append(task)
|
||||
|
||||
await interaction.followup.send('\n'.join(tasks))
|
||||
|
||||
except Exception as e:
|
||||
await interaction.followup.send(f'An error occurred: {e}')
|
||||
|
||||
|
||||
#Weather commad tree
|
||||
@bot.tree.command(name="weather")
|
||||
async def current_weather(interaction: discord.Interaction, location: str):
|
||||
|
||||
print(f"Received weather command from {interaction.user.display_name}") # Log intéraction
|
||||
|
||||
current_weather = weather_client.get_current_weather(location)
|
||||
|
||||
print(f"JSON API {current_weather}")
|
||||
|
||||
# Check that current_weather is a dictionary and contains necessary keys
|
||||
if not isinstance(current_weather, dict) or 'main' not in current_weather or 'weather' not in current_weather:
|
||||
await interaction.response.send_message("Could not retrieve weather data. Please check the location.")
|
||||
return
|
||||
|
||||
weather_list = current_weather['weather']
|
||||
if len(weather_list) == 0:
|
||||
await interaction.response.send_message("Weather information is not available.")
|
||||
return
|
||||
|
||||
weather_condition = weather_list[0]['main']
|
||||
|
||||
temp = current_weather['main']['temp']
|
||||
|
||||
icon = current_weather['weather']['icon']
|
||||
embed = discord.Embed(
|
||||
title=f"Current weather in {location}",
|
||||
description=f"Temperature: {temp}°C\nSky: {weather_condition}",
|
||||
)
|
||||
embed.set_thumbnail(url=f"https://openweathermap.org/img/wn/{icon}.png")
|
||||
|
||||
await interaction.response.send_message(embed=embed)
|
||||
|
||||
|
||||
@bot.tree.command(name='hello')
|
||||
async def hello_command(interaction: discord.Interaction):
|
||||
|
||||
print(f"Received hello command from {interaction.user.display_name}") # Log intéraction
|
||||
|
||||
user_nick = interaction.user.display_name
|
||||
await interaction.response.send_message(f'Hello {user_nick}!')
|
||||
|
||||
@bot.event
|
||||
async def on_ready():
|
||||
print(f'Logged in as {bot.user}')
|
||||
await bot.tree.sync()
|
||||
|
||||
#Liste commandes enregistré
|
||||
commands = await bot.tree.fetch_commands()
|
||||
print("Registered Commands:")
|
||||
for command in commands:
|
||||
print(f"- {command.name}")
|
||||
|
||||
bot.run(DISCORD_TOKEN)
|
||||
Loading…
x
Reference in New Issue
Block a user