-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
466 lines (404 loc) · 20.3 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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
import os
import discord
from discord.ext import commands,tasks
from dotenv import load_dotenv
import requests
from discord import app_commands
from datetime import datetime
from logs import log_writer,error_logs
import google.generativeai as genai
from random import choice,randint
from itertools import cycle
import asyncio
from discord.ui import View, Button
from newsapi import NewsApiClient
from datetime import datetime,timedelta
load_dotenv()
token = os.getenv('DISCORD_TOKEN')
intents = discord.Intents.default()
bot = commands.Bot(command_prefix='/', intents=intents)
genai.configure(api_key=os.getenv('GENAI'))
generation_config={"temperature":0.9,"top_p":1,"top_k":1,"max_output_tokens":300}
model=genai.GenerativeModel("gemini-1.5-pro",generation_config=generation_config)
bot_statuses=cycle(["/help & /info","my poppo","/help & /info","to his heartbeat"])
@tasks.loop(seconds=60)
async def change_status()->None:
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name=next(bot_statuses)), status=discord.Status.online)
channel_counters = {}
@bot.event
async def on_message(message:str)->None:
if message.author == bot.user:
return
if message.channel not in channel_counters:
channel_counters[message.channel] = 0
channel_counters[message.channel] += 1
if channel_counters[message.channel] == 10:
await message.channel.send("Oho i'm enjoying this!")
channel_counters[message.channel] = 0
await bot.process_commands(message)
@bot.tree.command(name="hello", description="Say hello to the bot!")
async def hello(interaction: discord.Interaction)->None:
try:
greets=[f"Hello there {interaction.user.mention}!",f"{interaction.user.mention} Still alive? 🤭",f"Nom was just thinking about you {interaction.user.mention} 🤗"]
await interaction.response.send_message(greets[randint(0,2)])
log_writer(interaction)
print('Hello Success')
except Exception as e:
log_writer(interaction)
print('Hello failed')
@bot.tree.command(name="weather",description="Get a quick weather update.")
@app_commands.describe(location="Enter your Location: ")
async def weather(interaction: discord.Integration,location:str)->None:
weather=os.getenv('WEATHER_API')
BASE_URL = "https://api.openweathermap.org/data/2.5/weather?"
url = BASE_URL + "appid=" + weather + "&q=" + location
try:
response = requests.get(url).json()
temp = response['main']['temp']
temp = temp-273.15
f_temp="The temperature is {:.0f}°C".format(temp)
humidity = response['main']['humidity']
humid="Humidity is "+ str(humidity)+"%"
feels_like="it feels like "+f"{response['main']['feels_like']-273.15:.0f}°C"
await interaction.response.send_message(f"{interaction.user.mention} {f_temp} and {feels_like} . {humid} .", ephemeral=True)
log_writer(interaction)
print("Weather success.")
except Exception as e:
log_writer(interaction)
error_logs(response)
print("Weather failed.")
await interaction.response.send_message(f"{interaction.user.mention} Invalid city name.", ephemeral=True)
@bot.tree.command(name="business_news",description="Get latest business updates.")
@app_commands.describe(country_code="Enter your country code: ")
async def news(interaction: discord.Integration,country_code:str)->None:
try:
api_endpoint="https://newsapi.org/v2/top-headlines"
params={
"country":{country_code},
"apiKey": os.getenv('NEWS_API'),
"category":"business"
}
response = requests.get(api_endpoint,params=params)
response=response.json()
embed=discord.Embed(colour=discord.Colour.dark_orange(),title="Latest Business News")
embed.set_author(icon_url="https://i.pinimg.com/564x/9a/bf/a0/9abfa0dc5ae0442470e9214453c3d7d2.jpg",name="Nom")
urls=[]
for i in range(0,5):
x=response["articles"][i]["description"]
if x==None:
x=""
if response["articles"][i]["title"]=="[Removed]":
continue
embed.add_field(name=f'{i+1}) {response["articles"][i]["title"]}', value=f'{x}\n\n', inline=False)
urls.append(response["articles"][i]["url"])
view1 = MyView4(urls)
await interaction.response.send_message(embed=embed,view=view1)
log_writer(interaction)
print('News fetch successful')
except Exception as e:
await interaction.response.send_message("News fetch unsuccessful",ephemeral=True)
log_writer(interaction)
print('News fetch successful')
error_logs(f"Error: {e}")
class MyView4(View):
def __init__(self,urls):
super().__init__()
num=["1st","2nd","3rd","4th","5th"]
for i in range(0,len(urls)):
self.add_item(Button(label=f"{num[i]}", style=discord.ButtonStyle.link, url=f'{urls[i]}', emoji="💼"))
@bot.tree.command(name="sports_news",description="Get latest sports updates.")
@app_commands.describe(country_code="Enter your country code: ")
async def news(interaction: discord.Integration,country_code:str)->None:
try:
api_endpoint="https://newsapi.org/v2/top-headlines"
params={
"country":{country_code},
"apiKey": os.getenv('NEWS_API'),
"category":"sports"
}
response = requests.get(api_endpoint,params=params)
response=response.json()
embed=discord.Embed(colour=discord.Colour.dark_orange(),title="Latest Sports News")
embed.set_author(icon_url="https://i.pinimg.com/564x/9a/bf/a0/9abfa0dc5ae0442470e9214453c3d7d2.jpg",name="Nom")
urls=[]
for i in range(0,5):
x=response["articles"][i]["description"]
if x==None:
x=""
if response["articles"][i]["title"]=="[Removed]":
continue
embed.add_field(name=f'{i+1}) {response["articles"][i]["title"]}', value=f'{x}\n\n', inline=False)
urls.append(response["articles"][i]["url"])
view1 = MyView3(urls)
await interaction.response.send_message(embed=embed,view=view1)
log_writer(interaction)
print('News fetch successful')
except Exception as e:
await interaction.response.send_message("News fetch unsuccessful",ephemeral=True)
log_writer(interaction)
print('News fetch unsuccessful')
error_logs(f"Error: {e}")
class MyView3(View):
def __init__(self,urls):
super().__init__()
num=["1st","2nd","3rd","4th","5th"]
for i in range(0,len(urls)):
self.add_item(Button(label=f"{num[i]}", style=discord.ButtonStyle.link, url=f'{urls[i]}', emoji="⚽"))
@bot.tree.command(name="news",description="Get latest news updates.")
@app_commands.describe(country_code="Enter your country code: ")
async def news(interaction: discord.Integration,country_code:str)->None:
try:
api_endpoint="https://newsapi.org/v2/top-headlines"
params={
"country":{country_code},
"apiKey": os.getenv('NEWS_API')
}
response = requests.get(api_endpoint,params=params)
response=response.json()
embed=discord.Embed(colour=discord.Colour.dark_orange(),title="Breaking News")
embed.set_author(icon_url="https://i.pinimg.com/564x/9a/bf/a0/9abfa0dc5ae0442470e9214453c3d7d2.jpg",name="Nom")
urls=[]
for i in range(0,5):
x=response["articles"][i]["description"]
if x==None:
x=""
if response["articles"][i]["title"]=="[Removed]":
continue
embed.add_field(name=f'{i+1}) {response["articles"][i]["title"]}', value=f'{x}\n\n', inline=False)
urls.append(response["articles"][i]["url"])
view1 = MyView2(urls)
await interaction.response.send_message(embed=embed,view=view1)
log_writer(interaction)
print('News fetch successful')
except Exception as e:
await interaction.response.send_message("News fetch unsuccessful",ephemeral=True)
error_logs(f"Error: {e}")
log_writer(interaction)
print('News fetch unsuccessful')
class MyView2(View):
def __init__(self,urls):
super().__init__()
num=["1st","2nd","3rd","4th","5th"]
for i in range(0,len(urls)):
self.add_item(Button(label=f"{num[i]}", style=discord.ButtonStyle.link, url=f'{urls[i]}', emoji="🗞️"))
@bot.tree.command(name="search",description="Search in Gemini.")
@app_commands.describe(search="Enter your prompt: ")
async def search(interaction: discord.Integration,search:str)->None:
await interaction.response.defer(ephemeral=True)
response= model.generate_content(["Never give answers in form of points or bullets."+search])
try:
s=response.text
last_dot_index = s.rfind(".")
if last_dot_index != -1:
s = s[:last_dot_index+1]
response = s
await interaction.followup.send(f"{response}", ephemeral=True)
log_writer(interaction)
print('Search successful')
except:
log_writer(interaction)
print('Search unsuccessful')
error_logs(response)
await interaction.response.send_message(f"{interaction.user.mention} Search unsuccessful .", ephemeral=True)
@bot.tree.command(name="score_matchday",description="Get all matchday updates.")
@app_commands.describe(league="Enter league code: ")
async def league_tables(interaction: discord.Integration,league:str)->None:
api_endpoint = f"https://api.football-data.org/v4/competitions/{league.upper()}/matches"
params = {
"season":2024
}
api_key = os.getenv('SCORES_API')
headers = {
"X-Auth-Token": api_key
}
response = requests.get(api_endpoint, headers=headers,params=params)
y=""
try:
data = response.json()
x=len(data["matches"])
y+=f' {data["competition"]["name"]}\n\n'
y+=f' Match Day - {data["matches"][0]["season"]["currentMatchday"]} - {data["matches"][data["resultSet"]["played"]]["stage"]}\n\n'
for i in range(0,x):
current_matchday=data["matches"][i]["matchday"]
if data["matches"][i]['season']['currentMatchday']==data["matches"][i]["matchday"]:
home_score=data["matches"][i]["score"]["fullTime"]["home"]
away_score=data["matches"][i]["score"]["fullTime"]["away"]
if home_score==None:
home_score='TBP'
away_score='TBP'
y = y + f'\t{data["matches"][i]["homeTeam"]["tla"]} {home_score:3} - {away_score:<3}'
if data["matches"][i]["score"]["duration"]=="PENALTY_SHOOTOUT":
y+="(P)"
y+=f' {data["matches"][i]["awayTeam"]["tla"]}\n\n'
else:
y+=f' {data["matches"][i]["awayTeam"]["tla"]}\n\n'
await interaction.response.send_message(f'```{y}```')
log_writer(interaction)
print('Score fetch successful')
except:
log_writer(interaction)
print("Score fetch failed.")
error_logs(f"Error: {response.status_code}")
await interaction.response.send_message('Failed to fetch',ephemeral=True)
@bot.tree.command(name="score_league",description="Get football league tables and group tables.")
@app_commands.describe(league="Enter league code: ")
async def league_tables(interaction: discord.Integration,league:str)->None:
api_endpoint = f"https://api.football-data.org/v4/competitions/{league.upper()}/standings"
api_key = os.getenv('SCORES_API')
headers = {
"X-Auth-Token": os.getenv('SCORES_API')
}
response = requests.get(api_endpoint, headers=headers)
x=''
try:
data = response.json()
number_of_teams=len(data["standings"][0]["table"])
number_of_groups=len(data["standings"])
x=x+f' {data["competition"]["name"]} - {data["filters"]["season"]}\n\n'
for j in range(0,number_of_groups):
if data["standings"][j]["group"]!=None:
x=x+f'\n{data["standings"][j]["group"]}\n\n'
else:
pass
x=x+' Std Team P W D L Pt\n\n'
for i in range(0,int(number_of_teams)):
team_name = data["standings"][j]["table"][i]["team"]["tla"]
padded_name = team_name.split()[0][:12]
x=x+f' {data["standings"][j]["table"][i]["position"]:2} {padded_name:5}{data["standings"][j]["table"][i]["playedGames"]:3} {data["standings"][j]["table"][i]["won"]:3} {data["standings"][j]["table"][i]["draw"]:2} {data["standings"][j]["table"][i]["lost"]:2} {data["standings"][j]["table"][i]["points"]:2}\n'
await interaction.response.send_message(f'```{x}```')
log_writer(interaction)
print('Score fetch successful')
except:
log_writer(interaction)
print("Score fetch failed.")
error_logs(f"Error: {response.status_code}")
await interaction.response.send_message('Failed to fetch',ephemeral=True)
@bot.tree.command(name="stock",description="Latest info about a stock.")
@app_commands.describe(ticker="Enter ticker: ")
async def stock(interaction: discord.Integration,ticker:str)->None:
stock_key=os.getenv('TICKER_API')
today = datetime.now()
while True:
yesterday = today - timedelta(days=1)
if yesterday.weekday()<5:
break
today = yesterday
yesterday_str = str(yesterday)
x = yesterday_str.split()[0]
api_endpoint=f'https://api.polygon.io/v1/open-close/{ticker.upper()}/{x}?adjusted=true&apiKey={stock_key}'
try:
response=requests.get(api_endpoint)
response=response.json()
embed=discord.Embed(colour=discord.Colour.dark_orange(),title="Stock details.")
embed.set_author(icon_url="https://i.pinimg.com/564x/9a/bf/a0/9abfa0dc5ae0442470e9214453c3d7d2.jpg",name="Nom")
embed.add_field(name=f'**Date: ```{response["from"]}```**', value=f'', inline=False)
embed.add_field(name=f'**Ticker: ```{response["symbol"]}```**', value=f'', inline=False)
embed.add_field(name=f'**Open: ```${response["open"]}```**', value=f'', inline=False)
embed.add_field(name=f'**High: ```${response["high"]}```**', value=f'', inline=False)
embed.add_field(name=f'**Low: ```${response["low"]}```**', value=f'', inline=False)
embed.add_field(name=f'**Close: ```${response["close"]}```**', value=f'', inline=False)
embed.add_field(name=f'**Volume: ```{response["volume"]}```**', value=f'', inline=False)
await interaction.response.send_message(embed=embed)
log_writer(interaction)
print('Stock fetch successful')
except:
log_writer(interaction)
print("Stock fetch failed.")
error_logs(f"Error: {interaction}")
await interaction.response.send_message('Failed to fetch',ephemeral=True)
@bot.tree.command(name="help",description="Get a list of all commands.")
async def help(interaction: discord.Integration)->None:
try:
embed=discord.Embed(colour=discord.Colour.dark_orange(),title="Powers of Nom.")
embed.set_author(icon_url="https://i.pinimg.com/564x/9a/bf/a0/9abfa0dc5ae0442470e9214453c3d7d2.jpg",name="Nom")
# embed.add_field(name="**Hi**", value="\t**/info:** Info about Nom.\n **/hello:** Greets the user.\n **/weather:** Gives a quick weather forecast.\n **/search:** Search up anything.\n **/score_league:** Shows league tables and group stages.\n **/score_matchday:** Shows latest matchday game updates.\n **/score_help:** Scores help for competition codes.\n", inline=False)
embed.add_field(name='**General:**', value='''
**`/info`**: Info about Nom.
**`/hello`**: Greets the user.
**`/weather`**: Gives a quick weather forecast.
**`/search`**: Search up anything.
''', inline=False)
embed.add_field(name='**Football:**', value='''
**`/score_league:`**: Shows league tables and group stages.
**`/score_matchday:`**: Shows latest matchday game updates.
**`/score_help:`**: Scores help for competition codes.
**`/search`**: Search up anything.
''', inline=False)
embed.add_field(name='**News:**', value='''
**`/news:`**: Shows breaking news from desired country.
**`/sports_news:`**: Shows latest sports news from desired country.
**`/business_news:`**: Shows latest business related news.
''', inline=False)
embed.add_field(name='**Stocks:**', value='''
**`/stock:`**: Shows desired stock info.
''', inline=False)
view=MyView5()
await interaction.response.send_message(embed=embed,view=view)
log_writer(interaction)
print('Help Success')
except Exception as e:
log_writer(interaction)
print('Help failed')
error_logs(e)
await interaction.response.send_message('Help failed',ephemeral=True)
class MyView5(View):
def __init__(self):
super().__init__()
self.add_item(Button(label=f"News Country codes", style=discord.ButtonStyle.link, url=f'https://newsapi.org/docs/endpoints/top-headlines'))
class MyView(View):
def __init__(self):
super().__init__()
self.add_item(Button(label="GitHub Repository", style=discord.ButtonStyle.link, url="https://github.com/ankitdey-marsh/Nom", emoji="🐙"))
@bot.tree.command(name="info",description="Get Nom info")
async def info(interaction: discord.Integration)->None:
try:
total_members = 0
for guild in bot.guilds:
total_members += guild.member_count
total_members-=len(bot.guilds)
embed=discord.Embed(colour=discord.Colour.dark_orange())
embed.set_author(icon_url="https://i.pinimg.com/564x/9a/bf/a0/9abfa0dc5ae0442470e9214453c3d7d2.jpg",name="Nom")
embed.add_field(name="",value="A multi-purpose Discord bot with gemini integration, football news,fetch weather report, and much more.",inline=False)
embed.add_field(name="Bot User",value=f"{bot.user}",inline=True)
embed.add_field(name="Guilds",value=f"{len(bot.guilds)}",inline=True)
embed.add_field(name="Members",value=f"{total_members}",inline=True)
embed.add_field(name="Prefix",value=f"/",inline=True)
embed.add_field(name="Webpage",value=f"[Official Nom](https://dub.sh/officialnom)",inline=True)
embed.add_field(name="Developer",
value="[Ankit Dey](https://dub.sh/ankitdey)",
inline=True)
embed.set_footer(text=f"© 2022-2024 Ankit Dey | Code licensed under the MIT License")
embed.set_image(
url="https://i.pinimg.com/736x/55/57/2a/55572a00eff9b0f0b4b836446d6ec476.jpg")
view = MyView()
await interaction.response.send_message(embed=embed, view=view)
log_writer(interaction)
print('Help Success')
except Exception as e:
log_writer(interaction)
print('Help failed')
error_logs(e)
await interaction.response.send_message('Help failed',ephemeral=True)
@bot.tree.command(name="score_help",description="Competition codes for scores.")
async def help(interaction: discord.Integration)->None:
try:
embed=discord.Embed(colour=discord.Colour.dark_orange(),title="Competition Codes.")
embed.set_author(icon_url="https://i.pinimg.com/564x/9a/bf/a0/9abfa0dc5ae0442470e9214453c3d7d2.jpg",name="Nom")
embed.add_field(name="", value="**World Cup** : **WC**\n**Premier League** : **PL**\n**La Liga** : **PD**\n**Ligue 1** : **FL1**\n**Bundesliga** : **BL1**\n**Serie A** : **SA**\n**Euro Cup** : **EC**\n**Eredivisie** : **DED**\n**Copa Libertadores** : **CLI**\n**Championship** : **ELC**\n**Campeonato Brasileiro Série A** : **BSA**\n", inline=False)
await interaction.response.send_message(embed=embed)
log_writer(interaction)
print('Help Success')
except Exception as e:
log_writer(interaction)
print('Help failed')
error_logs(e)
await interaction.response.send_message('Help failed',ephemeral=True)
@bot.event
async def on_ready()->None:
print(f'{bot.user} has connected to Discord!')
await bot.tree.sync()
change_status.start()
def main()->None:
bot.run(token)
if __name__=='__main__':
main()