110 lines
3.8 KiB
Python
110 lines
3.8 KiB
Python
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
|
|
|
|
global service
|
|
service = None
|
|
|
|
SCOPES = ['https://www.googleapis.com/auth/calendar.readonly']
|
|
service = None
|
|
|
|
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:
|
|
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()
|
|
async def events(interaction: discord.Interaction):
|
|
if service is None:
|
|
await interaction.response.send_message('Please authenticate first using the command authenticate.')
|
|
return
|
|
|
|
now = datetime.datetime.utcnow().isoformat() + 'Z'
|
|
events_result =service.events().list(calendarId='primary', timeMin=now, maxResults=1, singleEvents=True, orderBy='startTime').execute()
|
|
events = events_result.get('items', [])
|
|
|
|
if not events:
|
|
await interaction.response.send_message('No upcoming events found.')
|
|
else:
|
|
event_list = "\n".join([f"{event['start'].get('dateTime', event['start'].get('date'))}: {event['summary']}" for event in events])
|
|
await interaction.response.send_message(event_list)
|
|
|
|
|
|
|
|
#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)
|