-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
89 lines (76 loc) · 3.29 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
from typing import Final
from telegram import Update
from telegram.ext import Application, CallbackContext, ContextTypes
import pandas as pd
import requests
from datetime import datetime, timedelta
import logging
import io
import asyncio
from dotenv import load_dotenv
import os
import gspread
from google.oauth2.service_account import Credentials
# Get environment variables
load_dotenv()
TOKEN = os.getenv('BOT_TOKEN')
BOT_USERNAME: Final = '@GaruBdayBot'
# CHAT_ID = "-1002218572340" # Testing: HC Techies Chat
CHAT_ID = '-1002175948359' # Production: Garuda House Chat
TOPIC_THREAD_ID = '4' # Birthday Subtopic
SPREADSHEET_URL = 'https://docs.google.com/spreadsheets/d/1H684nLTxJn2vQOCR1Zhv1CiqNAt535Q9yhHQCGaXqIw/edit?pli=1&gid=1262152600#gid=1262152600'
# Configure logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
logger = logging.getLogger(__name__)
async def check_birthdays(application: Application):
today = (datetime.now() + timedelta(hours=8)).strftime('%d/%m') # Add 8 hours to work around UTC timings
try:
# Initialise and read from Google Sheets
scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"]
credentials = Credentials.from_service_account_file("service-account-key.json", scopes=scope)
gc = gspread.authorize(credentials) # Authenticate and initialize the gspread client
spreadsheet = gc.open_by_url(SPREADSHEET_URL)
sheet = spreadsheet.get_worksheet(0)
data = sheet.get_all_values() # Get all values in the sheet
df = pd.DataFrame(data[1:], columns=data[0]) # Convert the data to a Pandas DataFrame
for index, row in df.iterrows():
if today == row['Birthday']:
await application.bot.send_message(
chat_id=CHAT_ID,
text=f"Happy Birthday {row['Name']}!",
message_thread_id=TOPIC_THREAD_ID
)
except Exception as e:
logger.error(f"Failed to fetch or process Google Sheet: {e}")
"""
CSV_URL = "https://raw.githubusercontent.com/Garuda-Techs/GaruBdayBot/main/birthdays.csv"
async def check_birthdays(application: Application):
today = datetime.now().strftime('%d/%m')
try:
response = requests.get(CSV_URL)
response.raise_for_status() # Ensure we notice bad responses
df = pd.read_csv(io.StringIO(response.text))
for index, row in df.iterrows():
if today == row['Birthday']:
await application.bot.send_message(
chat_id=CHAT_ID,
text=f"Happy Birthday {row['Name']}!",
message_thread_id=TOPIC_THREAD_ID
)
except Exception as e:
logger.error(f"Failed to fetch or process CSV: {e}")
"""
async def error(update: Update, context: ContextTypes.DEFAULT_TYPE):
logger.error(f'Update {update} caused error {context.error}')
async def main():
print('Starting bot...')
app = Application.builder().token(TOKEN).build()
# Errors
app.add_error_handler(error)
# Initialize and start the application, then check birthdays
await app.initialize()
await app.start()
await check_birthdays(app)
await app.stop()
if __name__ == '__main__':
asyncio.run(main())