-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
152 lines (121 loc) · 5.4 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
from typing import List, Dict, AnyStr
import logging
import re
import asyncio
import time
import datetime
from mastoBot.configManager import ConfigAccessor
from mastoBot.mastoBot import MastoBot, handleMastodonExceptions
class MyBot(MastoBot):
@handleMastodonExceptions
def processMention(self, mention: Dict):
# Get the mention data
api_status = self.getStatus(mention.get("status"))
content = api_status.get("content")
mention_created_at = api_status.get("created_at")
# Get the account data
api_account = self.getAccount(mention.get("account"))
# Pattern for extracting time parameters
pattern = r'(?i)<span\s+class="h-card">\s*<a\s+href="https://techhub\.social/@remindMe"\s+class="u-url mention"[^>]*>@<span>remindMe</span></a>\s*</span>\s*(?:(?:(\d+)\s*years?)?\s*)?(?:(\d+)\s*months?)?\s*(?:(\d+)\s*weeks?)?\s*(?:(\d+)\s*days?)?\s*(?:(\d+)\s*hours?)?\s*(?:(\d+)\s*minutes?)?'
# Search for matches
matches = re.search(pattern, content)
# If matches are found
if matches:
# Extract data
years, months, weeks, days, hours, minutes = map(lambda x: int(x) if x else 0, matches.groups())
logging.info(f"Years: {years}, Months: {months}, Weeks: {weeks}, Days: {days}, Hours: {hours}, Minutes: {minutes}")
# Calculate delta time
delta = datetime.timedelta(
days=days + weeks * 7 + months * 30 + years * 365,
hours=hours,
minutes=minutes
)
if (years + months + weeks + days + hours + minutes <= 0):
logging.warning('Mention does not include non-zero time')
return
future_time = mention_created_at + delta
logging.info(f"Current Time: {mention_created_at}")
logging.info(f"Future Time: {future_time}")
# Create scheduled message
scheduled_reminder_message = bot.getTemplate(
file_name='scheduled_reminder.txt',
data={
'account': api_account.get('acct'),
'requested_post_url': api_status.get('url')
})
# Create reply message
reply_message = bot.getTemplate(
file_name='reply_to_request.txt',
data={
'account': api_account.get('acct')
}
)
try:
# Post scheduled post
scheduled_post = bot._api.status_post(
status=scheduled_reminder_message,
scheduled_at=future_time,
visibility='direct'
)
# Post reply and acknowledging message
reply_post = bot._api.status_post(
status=reply_message,
in_reply_to_id=api_status.get('id'),
visibility='direct'
)
logging.info(f'new scheduled post: {scheduled_post}')
logging.info(f'new reply post: {reply_post}')
# Favourite their request message
bot.favoriteStatus(api_status.get('id'))
# Dismiss the notification
logging.info(f"📬 \t Mention processed: {mention.get('id')}")
self.dismissNotification(mention.get("id"))
except:
pass
@handleMastodonExceptions
def processReblog(self, reblog: Dict):
self.dismissNotification(reblog.get("id"))
@handleMastodonExceptions
def processFavourite(self, favourite: Dict):
self.dismissNotification(favourite.get("id"))
@handleMastodonExceptions
def processFollow(self, follow: Dict):
# Get latest account from the Mastodon API
api_account = self.getAccount(follow.get("account"))
account = api_account.get("acct")
template_data = {"account": account}
# Generate the welcoming message from the template
try:
output = self.getTemplate("new_follow.txt", template_data)
self._api.status_post(status=output, visibility="direct")
except Exception as e:
logging.critical("❗ \t Error posting Status")
raise e
logging.info(f"📭 \t Follow processed: {follow.get('id')}")
self.dismissNotification(follow.get("id"))
@handleMastodonExceptions
def processPoll(self, poll: Dict):
self.dismissNotification(poll.get("id"))
@handleMastodonExceptions
def processFollowRequest(self, follow_request: Dict):
self.dismissNotification(follow_request.get("id"))
@handleMastodonExceptions
def processUpdate(self, update: Dict) -> None:
self.dismissNotification(update.get("id"))
if __name__ == "__main__":
config = ConfigAccessor("config.yml")
credentials = ConfigAccessor("credentials.yml")
bot = MyBot(credentials=credentials, config=config)
async def runBot():
while True:
logging.info("✅ \t Running bot")
await bot.run()
await asyncio.sleep(10)
async def main():
await asyncio.gather(runBot())
while True:
try:
asyncio.run(main())
except:
time.sleep(10)
pass