-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot.py
2003 lines (1802 loc) · 76.4 KB
/
bot.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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# bot.py
import os
import discord
from discord.ext import commands
from discord.ui import Button, View
from dotenv import load_dotenv
import requests
import random
import asyncio
import logging
import json
from datetime import datetime
from discord import Activity, ActivityType
# Load environment variables from .env file
load_dotenv()
# Retrieve API keys and tokens from environment variables
BOT_TOKEN = os.getenv("BOT_TOKEN")
TENOR_API_KEY = os.getenv("TENOR_API_KEY")
NEWS_API_KEY = os.getenv("NEWS_API_KEY")
OMDB_API_KEY = os.getenv("OMDB_API_KEY")
ALPHA_VANTAGE_API_KEY = os.getenv("ALPHA_VANTAGE_API_KEY")
NASA_API_KEY = os.getenv("NASA_API_KEY")
GITHUB_TOKEN = os.getenv("GITHUB_TOKEN") # Optional: For authenticated GitHub API requests
# Validate essential API keys
required_keys = {
"BOT_TOKEN": BOT_TOKEN,
"TENOR_API_KEY": TENOR_API_KEY,
"NEWS_API_KEY": NEWS_API_KEY,
"OMDB_API_KEY": OMDB_API_KEY,
"ALPHA_VANTAGE_API_KEY": ALPHA_VANTAGE_API_KEY,
"NASA_API_KEY": NASA_API_KEY
}
missing_keys = [key for key, value in required_keys.items() if not value]
if missing_keys:
missing = ", ".join(missing_keys)
raise EnvironmentError(f"Missing required environment variables: {missing}")
# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger('discord')
# Define bot intents
intents = discord.Intents.default()
intents.message_content = True # Enable access to message content
# Initialize bot
bot = commands.Bot(command_prefix="!", intents=intents, description="InfoNexus - The Ultimate Discord Bot!")
# Initialize user data storage
USER_DATA_FILE = "user_data.json"
if not os.path.exists(USER_DATA_FILE):
with open(USER_DATA_FILE, "w") as f:
json.dump({}, f)
def load_user_data():
with open(USER_DATA_FILE, "r") as f:
return json.load(f)
def save_user_data(data):
with open(USER_DATA_FILE, "w") as f:
json.dump(data, f, indent=4)
@bot.event
async def on_ready():
await bot.change_presence(activity=Activity(type=ActivityType.watching, name="AnshKabra2012"))
print(f"Logged in as {bot.user}")
# Helper Functions
def fetch_trivia_question(category=None):
"""Fetch a trivia question from Open Trivia DB."""
base_url = "https://opentdb.com/api.php"
params = {"amount": 1}
if category:
category_map = {
"general": 9,
"books": 10,
"film": 11,
"music": 12,
"science": 17,
"computers": 18,
"math": 19,
"sports": 21,
"geography": 22,
"history": 23,
"politics": 24,
"art": 25,
"celebrities": 26,
"animals": 27,
"vehicles": 28,
"comics": 29,
"gadgets": 30,
"anime": 31,
"cartoon": 32
}
category_id = category_map.get(category.lower())
if category_id:
params["category"] = category_id
response = requests.get(base_url, params=params)
if response.status_code == 200:
data = response.json()
return data["results"][0] if data["results"] else None
return None
def fetch_random_fact():
"""Fetch a random fact from Useless Facts API."""
response = requests.get("https://uselessfacts.jsph.pl/random.json?language=en")
if response.status_code == 200:
return response.json().get("text", "No fact found.")
return "Couldn't fetch a fact right now."
def fetch_joke():
"""Fetch a random joke from Official Joke API."""
response = requests.get("https://official-joke-api.appspot.com/jokes/random")
if response.status_code == 200:
joke = response.json()
return f"{joke['setup']} - {joke['punchline']}"
return "Couldn't fetch a joke right now."
def fetch_quote():
"""Fetch a random inspirational quote from Quotable API."""
response = requests.get("https://api.quotable.io/random")
if response.status_code == 200:
data = response.json()
return f"\"{data['content']}\" - {data['author']}"
return "Couldn't fetch a quote right now."
def fetch_random_dog_image():
"""Fetch a random dog image from Dog CEO API."""
response = requests.get("https://dog.ceo/api/breeds/image/random")
if response.status_code == 200:
return response.json().get("message", "")
return ""
def fetch_random_cat_image():
"""Fetch a random cat image from TheCatAPI."""
response = requests.get("https://api.thecatapi.com/v1/images/search")
if response.status_code == 200:
data = response.json()
if data:
return data[0].get("url", "")
return ""
def fetch_spells():
"""Fetch spells from Harry Potter API."""
response = requests.get("https://hp-api.onrender.com/api/spells")
if response.status_code == 200:
return response.json()
return []
def fetch_random_meal():
"""Fetch a random meal from TheMealDB."""
response = requests.get("https://www.themealdb.com/api/json/v1/1/random.php")
if response.status_code == 200:
data = response.json()
if data.get("meals"):
return data["meals"][0]
return {}
def fetch_reddit_post(subreddit):
"""Fetch a random post from a subreddit."""
headers = {'User-agent': 'Mozilla/5.0'}
response = requests.get(f"https://www.reddit.com/r/{subreddit}/random.json", headers=headers)
if response.status_code == 200:
data = response.json()
if isinstance(data, list) and len(data) > 0:
post = data[0]['data']['children'][0]['data']
title = post.get("title", "No title")
url = post.get("url", "")
return title, url
return None, None
def fetch_github_user(username):
"""Fetch GitHub user information."""
headers = {}
if GITHUB_TOKEN:
headers['Authorization'] = f'token {GITHUB_TOKEN}'
response = requests.get(f"https://api.github.com/users/{username}", headers=headers)
if response.status_code == 200:
data = response.json()
name = data.get("name", "N/A")
bio = data.get("bio", "N/A")
repos = data.get("public_repos", 0)
followers = data.get("followers", 0)
following = data.get("following", 0)
avatar = data.get("avatar_url", "")
return name, bio, repos, followers, following, avatar
return None
def fetch_movie_info(title):
"""Fetch movie information from OMDB API."""
response = requests.get(f"http://www.omdbapi.com/?t={title}&apikey={OMDB_API_KEY}")
if response.status_code == 200:
data = response.json()
if data.get("Response") == "True":
title = data.get("Title", "N/A")
year = data.get("Year", "N/A")
genre = data.get("Genre", "N/A")
director = data.get("Director", "N/A")
plot = data.get("Plot", "N/A")
poster = data.get("Poster", "")
return title, year, genre, director, plot, poster
return None
def fetch_alpha_vantage_stock(symbol):
"""Fetch stock price from Alpha Vantage API."""
response = requests.get(
f"https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol={symbol}&apikey={ALPHA_VANTAGE_API_KEY}"
)
if response.status_code == 200:
data = response.json()
quote = data.get("Global Quote", {})
price = quote.get("05. price", "N/A")
change = quote.get("09. change", "N/A")
return price, change
return None, None
def fetch_bitcoin_price():
"""Fetch current Bitcoin price in USD from Coindesk API."""
response = requests.get("https://api.coindesk.com/v1/bpi/currentprice/BTC.json")
if response.status_code == 200:
data = response.json()
rate = data["bpi"]["USD"]["rate"]
return rate
return "Couldn't fetch Bitcoin price right now."
def fetch_nasa_apod():
"""Fetch NASA Astronomy Picture of the Day."""
response = requests.get(f"https://api.nasa.gov/planetary/apod?api_key={NASA_API_KEY}")
if response.status_code == 200:
data = response.json()
title = data.get("title", "N/A")
explanation = data.get("explanation", "N/A")
url = data.get("url", "")
return title, explanation, url
return None, None, None
def fetch_tenor_gif(tag="random"):
"""Fetch a random GIF from Tenor."""
response = requests.get(f"https://tenor.googleapis.com/v2/search?q={tag}&key={TENOR_API_KEY}&limit=1")
if response.status_code == 200:
results = response.json().get("results", [])
if results:
media = results[0].get("media_formats", {})
gif = media.get("gif", {}).get("url")
if gif:
return gif
return None
def fetch_trending_repositories():
"""Fetch trending repositories from GitHub Trending API."""
# Note: GitHub doesn't provide an official trending API. Using a third-party API.
response = requests.get("https://ghapi.huchen.dev/repositories?since=daily")
if response.status_code == 200:
data = response.json()
trending_repos = [f"**{repo['name']}** by **{repo['author']}**\n[Repository]({repo['url']})" for repo in data[:5]]
return trending_repos
return ["Couldn't fetch trending repositories right now."]
def fetch_random_fact_about_number(number):
"""Fetch a fact about a number from Numbers API."""
response = requests.get(f"http://numbersapi.com/{number}/trivia")
if response.status_code == 200:
return response.text
return "Couldn't fetch a number fact right now."
def fetch_random_fortune():
"""Fetch a random fortune from a static list."""
fortunes = [
"You will have a great day!",
"Success is in your future.",
"Adventure awaits you.",
"Embrace the challenges ahead.",
"A pleasant surprise is waiting for you."
]
return random.choice(fortunes)
def fetch_random_meme():
"""Fetch a random meme from Meme API."""
response = requests.get("https://meme-api.herokuapp.com/gimme")
if response.status_code == 200:
data = response.json()
title = data.get("title", "No title")
url = data.get("url", "")
return title, url
return None, None
def fetch_dad_joke():
"""Fetch a random dad joke from icanhazdadjoke API."""
headers = {'Accept': 'application/json'}
response = requests.get("https://icanhazdadjoke.com/", headers=headers)
if response.status_code == 200:
data = response.json()
return data.get("joke", "Couldn't fetch a joke right now.")
return "Couldn't fetch a joke right now."
def fetch_random_fox_image():
"""Fetch a random fox image from randomfox.ca."""
response = requests.get("https://randomfox.ca/floof/")
if response.status_code == 200:
data = response.json()
return data.get("image", "")
return ""
def fetch_inspirational_story():
"""Fetch an inspirational story from a static list."""
inspirational_stories = [
"Once upon a time, in a land far, far away, there lived a brave adventurer who overcame all odds to achieve their dreams.",
"In the heart of the forest, a small seed grew into a mighty tree, symbolizing resilience and growth.",
"Through persistent effort and unwavering determination, she conquered her fears and soared to new heights.",
"Against all expectations, the underdog team triumphed, teaching us that perseverance pays off.",
"He turned his failures into stepping stones, proving that every setback is a setup for a comeback."
]
return random.choice(inspirational_stories)
def fetch_horoscope(sign):
"""Fetch daily horoscope from Horoscope API."""
response = requests.post(f"https://aztro.sameerkumar.website/?sign={sign.lower()}&day=today")
if response.status_code == 200:
data = response.json()
horoscope = data.get("description", "No horoscope found.")
return horoscope
return "Couldn't fetch horoscope right now."
def fetch_dictionary_definition(word):
"""Fetch the definition of a word from Dictionary API."""
response = requests.get(f"https://api.dictionaryapi.dev/api/v2/entries/en/{word}")
if response.status_code == 200:
data = response.json()[0]
definitions = data["meanings"][0]["definitions"][0]["definition"]
example = data["meanings"][0]["definitions"][0].get("example", "No example provided.")
return definitions, example
return None, None
def fetch_random_activity():
"""Fetch a random activity suggestion from Bored API."""
response = requests.get("https://www.boredapi.com/api/activity/")
if response.status_code == 200:
data = response.json()
return data.get("activity", "Couldn't fetch an activity right now.")
return "Couldn't fetch an activity right now."
def fetch_random_music_quote():
"""Fetch a random music-related quote from a static list."""
music_quotes = [
"Music is the universal language of mankind. – Henry Wadsworth Longfellow",
"Where words fail, music speaks. – Hans Christian Andersen",
"Without music, life would be a mistake. – Friedrich Nietzsche",
"One good thing about music, when it hits you, you feel no pain. – Bob Marley",
"Music expresses that which cannot be said and on which it is impossible to be silent. – Victor Hugo"
]
return random.choice(music_quotes)
def fetch_random_art_quote():
"""Fetch a random art-related quote from a static list."""
art_quotes = [
"Every artist was first an amateur. – Ralph Waldo Emerson",
"Art is not what you see, but what you make others see. – Edgar Degas",
"Creativity takes courage. – Henri Matisse",
"Art enables us to find ourselves and lose ourselves at the same time. – Thomas Merton",
"The purpose of art is washing the dust of daily life off our souls. – Pablo Picasso"
]
return random.choice(art_quotes)
def fetch_random_math_fact():
"""Fetch a random math fact from a static list."""
math_facts = [
"Zero is the only number that cannot be represented by Roman numerals.",
"A triangle has three sides, a square has four.",
"The number pi is irrational.",
"There are infinitely many prime numbers.",
"Euler's identity is considered the most beautiful theorem in mathematics."
]
return random.choice(math_facts)
def fetch_random_geography_fact():
"""Fetch a random geography fact from a static list."""
geography_facts = [
"Canada has the longest coastline in the world.",
"Russia is the largest country by area.",
"There are seven continents on Earth.",
"The Amazon River is the largest by discharge volume.",
"Mount Everest is the highest mountain above sea level."
]
return random.choice(geography_facts)
def fetch_random_politics_fact():
"""Fetch a random politics fact from a static list."""
politics_facts = [
"The United Nations has 193 member states.",
"The first female Prime Minister was Sirimavo Bandaranaike of Sri Lanka.",
"The term 'democracy' comes from the Greek words 'demos' and 'kratos'.",
"There are over 200 recognized political systems globally.",
"The longest-serving head of state was King Bhumibol Adulyadej of Thailand."
]
return random.choice(politics_facts)
def fetch_random_computer_fact():
"""Fetch a random computer fact from a static list."""
computer_facts = [
"The first computer bug was a moth trapped in a Harvard Mark II computer.",
"The QWERTY keyboard was designed to prevent typewriter jams.",
"The first computer virus was created in 1983.",
"Approximately 90% of the world's data has been created in the last two years.",
"The term 'debugging' was popularized by Grace Hopper."
]
return random.choice(computer_facts)
def fetch_random_cinema_fact():
"""Fetch a random cinema fact from a static list."""
cinema_facts = [
"The first feature-length film was 'The Story of the Kelly Gang' (1906).",
"Avatar is the highest-grossing film of all time.",
"Gone with the Wind was the first film to earn over $1 billion.",
"The silent film era lasted from the late 1890s to the late 1920s.",
"Pixar's 'Toy Story' was the first entirely computer-animated feature film."
]
return random.choice(cinema_facts)
def fetch_random_religion_fact():
"""Fetch a random religion fact from a static list."""
religion_facts = [
"There are over 4,000 religions in the world.",
"Buddhism originated in India around the 5th century BCE.",
"Christianity is the largest religion globally.",
"Islam was founded in the 7th century CE in Mecca.",
"Hinduism is the oldest living religion."
]
return random.choice(religion_facts)
def fetch_random_physics_fact():
"""Fetch a random physics fact from a static list."""
physics_facts = [
"Light can behave both as a wave and as a particle.",
"Einstein's theory of relativity revolutionized physics.",
"Quantum entanglement is a phenomenon where particles remain connected.",
"The speed of light is approximately 299,792 kilometers per second.",
"Black holes are regions in space with gravitational pulls so strong that nothing can escape."
]
return random.choice(physics_facts)
def fetch_random_technology_fact():
"""Fetch a random technology fact from a static list."""
technology_facts = [
"The first computer was invented in the 1940s.",
"The internet was initially developed for military use.",
"Over 3 billion people use the internet worldwide.",
"Artificial Intelligence is a rapidly growing field in technology.",
"Blockchain technology underpins cryptocurrencies like Bitcoin."
]
return random.choice(technology_facts)
def fetch_random_environment_fact():
"""Fetch a random environment fact from a static list."""
environment_facts = [
"The Amazon rainforest produces over 20% of the world's oxygen.",
"Plastic pollution is one of the biggest threats to marine life.",
"Renewable energy sources are crucial for combating climate change.",
"Deforestation contributes to the loss of biodiversity.",
"Recycling helps reduce greenhouse gas emissions."
]
return random.choice(environment_facts)
def fetch_random_entertainment_fact():
"""Fetch a random entertainment fact from a static list."""
entertainment_facts = [
"The Grammy Awards were established in 1959.",
"The Oscars statuette is made of gold-plated britannium.",
"MTV was launched on August 1, 1981.",
"The Super Bowl is one of the most-watched sporting events in the US.",
"Broadway in New York City is known for its theater productions."
]
return random.choice(entertainment_facts)
def fetch_random_fashion_fact():
"""Fetch a random fashion fact from a static list."""
fashion_facts = [
"The little black dress became popular thanks to Coco Chanel.",
"Blue jeans were invented by Levi Strauss in the 1870s.",
"The first fashion magazine was published in Germany in 1586.",
"Heels were originally worn by men in the 10th century.",
"Nike is one of the largest sportswear brands in the world."
]
return random.choice(fashion_facts)
def fetch_random_lifestyle_fact():
"""Fetch a random lifestyle fact from a static list."""
lifestyle_facts = [
"Meditation can reduce stress and improve focus.",
"A balanced diet is essential for maintaining good health.",
"Regular exercise boosts mental and physical well-being.",
"Adequate sleep is crucial for overall health.",
"Hydration plays a key role in bodily functions."
]
return random.choice(lifestyle_facts)
def fetch_random_animals_fact():
"""Fetch a random animals fact from a static list."""
animals_facts = [
"Honey never spoils. Archaeologists have found pots of honey in ancient Egyptian tombs that are over 3,000 years old and still edible.",
"A group of flamingos is called a 'flamboyance'.",
"Octopuses have three hearts.",
"Dolphins have names for each other.",
"Elephants are the only animals that can't jump."
]
return random.choice(animals_facts)
def fetch_random_artistic_fact():
"""Fetch a random artistic fact from a static list."""
artistic_facts = [
"Leonardo da Vinci could write with one hand and draw with the other simultaneously.",
"Vincent van Gogh only sold one painting during his lifetime.",
"The Mona Lisa has no eyebrows. It was the fashion in Renaissance Florence to shave them off.",
"The word 'palette' comes from the Italian word for a small shovel used by artists.",
"Pablo Picasso could draw before he could walk."
]
return random.choice(artistic_facts)
def fetch_random_philosophy_fact():
"""Fetch a random philosophy fact from a static list."""
philosophy_facts = [
"Socrates never wrote down his teachings; all knowledge of his philosophy comes from his students.",
"Plato founded the first institution of higher learning in the Western world.",
"Aristotle tutored Alexander the Great.",
"Immanuel Kant never traveled more than 10 miles from his hometown.",
"Friedrich Nietzsche declared 'God is dead' in his works."
]
return random.choice(philosophy_facts)
def fetch_random_game_fact():
"""Fetch a random game fact from a static list."""
game_facts = [
"The first video game ever created was 'Tennis for Two' in 1958.",
"Pac-Man was originally called 'Puck-Man', but was changed to avoid vandalism.",
"The character Mario was named after the landlord of Nintendo's warehouse in Brooklyn.",
"The iconic Konami Code (↑ ↑ ↓ ↓ ← → ← → B A) was first used in the game Gradius.",
"Minecraft is the best-selling video game of all time."
]
return random.choice(game_facts)
def fetch_random_comic():
"""Fetch a random xkcd comic."""
latest_comic_num = get_latest_comic_number()
if latest_comic_num:
random_num = random.randint(1, latest_comic_num)
response = requests.get(f"https://xkcd.com/{random_num}/info.0.json")
if response.status_code == 200:
data = response.json()
title = data.get("title", "N/A")
img = data.get("img", "")
alt = data.get("alt", "")
return title, img, alt
return None, None, None
def get_latest_comic_number():
"""Get the latest xkcd comic number."""
response = requests.get("https://xkcd.com/info.0.json")
if response.status_code == 200:
data = response.json()
return data.get("num")
return None
def fetch_random_book():
"""Fetch a random book from Open Library API."""
response = requests.get("https://openlibrary.org/random.json?count=1")
if response.status_code == 200:
data = response.json()
title = data.get("title", "N/A")
authors = ", ".join([author.get("name", "Unknown") for author in data.get("authors", [])])
description = data.get("description", {}).get("value", "No description available.") if isinstance(data.get("description"), dict) else data.get("description", "No description available.")
return title, authors, description
return None, None, None
def fetch_random_pokemon():
"""Fetch a random Pokémon from PokéAPI."""
pokemon_id = random.randint(1, 898) # As of now, there are 898 Pokémon
response = requests.get(f"https://pokeapi.co/api/v2/pokemon/{pokemon_id}")
if response.status_code == 200:
data = response.json()
name = data.get("name", "N/A").title()
image = data["sprites"]["front_default"]
types = ", ".join([t["type"]["name"].title() for t in data.get("types", [])])
return name, image, types
return None, None, None
def fetch_random_color():
"""Fetch a random color from The Color API."""
response = requests.get("https://www.thecolorapi.com/id?format=json&hex=random")
if response.status_code == 200:
data = response.json()
name = data.get("name", {}).get("value", "N/A")
hex_code = f"#{data.get('hex', {}).get('value', '000000')}"
return name, hex_code
return None, None
def fetch_random_weather_fact():
"""Fetch a random weather fact from a static list."""
weather_facts = [
"Lightning strikes the Earth about 100 times every second.",
"The highest temperature ever recorded on Earth was 56.7°C (134°F) in Death Valley, USA.",
"A single hurricane can release energy equivalent to a 10-megaton nuclear bomb every 20 minutes.",
"Rainbows can only be seen when the sun is less than 42 degrees above the horizon.",
"The coldest temperature ever recorded on Earth was -89.2°C (-128.6°F) in Antarctica."
]
return random.choice(weather_facts)
def fetch_random_space_fact():
"""Fetch a random space fact from a static list."""
space_facts = [
"A day on Venus is longer than a year on Venus.",
"There are more stars in the universe than grains of sand on all the beaches on Earth.",
"Neutron stars are so dense that a sugar-cube-sized amount would weigh about a billion tons.",
"The largest volcano in the solar system is Olympus Mons on Mars.",
"Space is completely silent; there is no atmosphere for sound to travel through."
]
return random.choice(space_facts)
def fetch_random_career_advice():
"""Fetch a random career advice from a static list."""
career_advice = [
"Always be willing to learn new skills.",
"Network with professionals in your field.",
"Set clear and achievable goals.",
"Seek feedback to improve your performance.",
"Maintain a healthy work-life balance."
]
return random.choice(career_advice)
def fetch_random_health_tip():
"""Fetch a random health tip from a static list."""
health_tips = [
"Drink at least 8 glasses of water a day.",
"Incorporate regular exercise into your routine.",
"Eat a balanced diet rich in fruits and vegetables.",
"Ensure you get 7-9 hours of sleep each night.",
"Practice mindfulness or meditation to reduce stress."
]
return random.choice(health_tips)
def fetch_random_travel_tip():
"""Fetch a random travel tip from a static list."""
travel_tips = [
"Always have a digital and physical copy of your important documents.",
"Learn a few basic phrases in the local language.",
"Keep your valuables secure and be aware of your surroundings.",
"Pack light and versatile clothing.",
"Research your destination's culture and customs beforehand."
]
return random.choice(travel_tips)
def fetch_random_sports_fact():
"""Fetch a random sports fact from a static list."""
sports_facts = [
"The Olympic Games were originally a religious festival in honor of Zeus.",
"Basketball was invented by Dr. James Naismith in 1891.",
"The FIFA World Cup is the most widely viewed sporting event in the world.",
"Golf is the only sport to have been played on the moon.",
"The fastest goal in soccer history was scored just 2.8 seconds after kickoff."
]
return random.choice(sports_facts)
def fetch_random_science_fact():
"""Fetch a random science fact from a static list."""
science_facts = [
"Water can boil and freeze at the same time under the right conditions, a phenomenon known as the triple point.",
"Bananas are berries, but strawberries are not.",
"Sound travels five times faster in water than in air.",
"There are more possible iterations of a game of chess than there are atoms in the known universe.",
"Venus spins clockwise, making it the only planet that rotates in this direction."
]
return random.choice(science_facts)
def fetch_random_history_fact():
"""Fetch a random history fact from a static list."""
history_facts = [
"The Great Wall of China is not visible from space with the naked eye.",
"Cleopatra lived closer in time to the moon landing than to the construction of the Great Pyramid of Giza.",
"The shortest war in history lasted only 38 minutes between Britain and Zanzibar in 1896.",
"Oxford University is older than the Aztec Empire.",
"The first programmable computer was created in 1936 by Konrad Zuse."
]
return random.choice(history_facts)
def fetch_random_literature_fact():
"""Fetch a random literature fact from a static list."""
literature_facts = [
"William Shakespeare introduced over 1,700 words to the English language.",
"The longest novel ever written is 'In Search of Lost Time' by Marcel Proust.",
"Agatha Christie is the best-selling novelist of all time.",
"The first printed book was the Diamond Sutra in 868 AD.",
"George Orwell's real name was Eric Arthur Blair."
]
return random.choice(literature_facts)
# Interactive Views
class TriviaView(View):
def __init__(self, correct_answer, options):
super().__init__(timeout=60)
self.correct_answer = correct_answer
self.options = options
for option in options:
button = Button(label=option, style=discord.ButtonStyle.primary)
button.callback = self.create_callback(option)
self.add_item(button)
def create_callback(self, selected_option):
async def callback(interaction: discord.Interaction):
if selected_option == self.correct_answer:
content = f"✅ Correct! The answer was: **{self.correct_answer}**"
else:
content = f"❌ Incorrect! The correct answer was: **{self.correct_answer}**"
# Disable all buttons after answer
for child in self.children:
child.disabled = True
await interaction.response.edit_message(content=content, view=self)
self.stop()
return callback
async def on_timeout(self):
# Disable all buttons on timeout
for child in self.children:
child.disabled = True
if hasattr(self, 'message'):
await self.message.edit(content="⏰ Time's up! You didn't answer in time.", view=self)
class HelpView(View):
def __init__(self, embeds):
super().__init__(timeout=180)
self.embeds = embeds
self.current = 0
# Previous Button
self.previous_button = Button(label="Previous", style=discord.ButtonStyle.secondary)
self.previous_button.callback = self.previous_page
self.add_item(self.previous_button)
# Next Button
self.next_button = Button(label="Next", style=discord.ButtonStyle.secondary)
self.next_button.callback = self.next_page
self.add_item(self.next_button)
async def previous_page(self, interaction: discord.Interaction):
if self.current > 0:
self.current -= 1
await interaction.response.edit_message(embed=self.embeds[self.current], view=self)
async def next_page(self, interaction: discord.Interaction):
if self.current < len(self.embeds) - 1:
self.current += 1
await interaction.response.edit_message(embed=self.embeds[self.current], view=self)
async def on_timeout(self):
# Disable buttons on timeout
for child in self.children:
child.disabled = True
if hasattr(self, 'message'):
await self.message.edit(view=self)
# Enforced Registration Decorator
def is_registered():
async def predicate(ctx):
user_data = load_user_data()
return str(ctx.author.id) in user_data
return commands.check(predicate)
# Commands
# 1. About Command
@bot.command(name="about", help="Get information about the bot. Usage: !about")
async def about(ctx):
# Fetch GitHub user data
github_username = "anshkabra2012"
github_data = fetch_github_user(github_username)
if github_data:
name, bio, repos, followers, following, avatar = github_data
embed = discord.Embed(
title="🤖 About InfoNexus",
description="Welcome to InfoNexus! I'm your ultimate Discord companion, here to provide you with a wealth of information, fun facts, and interactive experiences.",
color=discord.Color.blue()
)
embed.set_author(name=name, url=f"https://github.com/{github_username}", icon_url=avatar)
embed.add_field(
name="⭐ Star Our Project",
value="If you enjoy using me, please consider starring our GitHub repository!",
inline=False
)
embed.add_field(
name="💻 GitHub Repository",
value="[InfoNexus-discord-bot](https://github.com/anshkabra2012/InfoNexus-discord-bot)",
inline=False
)
embed.add_field(
name="📊 GitHub Stats",
value=f"**Public Repos:** {repos}\n**Followers:** {followers}\n**Following:** {following}",
inline=False
)
embed.set_thumbnail(url=avatar)
github_logo_url = "https://github.githubassets.com/images/modules/logos_page/GitHub-Mark.png"
embed.set_footer(text="Thank you for using InfoNexus!", icon_url=github_logo_url)
await ctx.send(embed=embed)
else:
embed = discord.Embed(
title="🤖 About InfoNexus",
description="Welcome to InfoNexus! I'm your ultimate Discord companion, here to provide you with a wealth of information, fun facts, and interactive experiences.",
color=discord.Color.blue()
)
embed.add_field(
name="⭐ Star Our Project",
value="If you enjoy using me, please consider starring our GitHub repository!",
inline=False
)
embed.add_field(
name="💻 GitHub Repository",
value="[InfoNexus-discord-bot](https://github.com/anshkabra2012/InfoNexus-discord-bot)",
inline=False
)
embed.set_footer(text="Thank you for using InfoNexus!", icon_url=github_logo_url)
await ctx.send(embed=embed)
# 2. Register Command
@bot.command(name="register", help="Register yourself to use the bot. Usage: !register <username>")
async def register(ctx, username: str = None):
if not username:
await ctx.send("❗ Please provide a username. Usage: `!register <username>`")
return
user_data = load_user_data()
user_data[str(ctx.author.id)] = {
"username": username,
"registered_at": datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S UTC")
}
save_user_data(user_data)
embed = discord.Embed(
title="✅ Registration Successful!",
description=f"Welcome, **{username}**! You can now access all the bot's features.",
color=discord.Color.green()
)
await ctx.send(embed=embed)
# 3. Trivia
@bot.command(name="trivia", help="Start a trivia game. Usage: !trivia [category]")
@is_registered()
async def trivia(ctx, category: str = "general"):
question = fetch_trivia_question(category)
if question:
embed = discord.Embed(
title="🎯 Trivia Time!",
description=question["question"],
color=discord.Color.blue()
)
answers = question["incorrect_answers"] + [question["correct_answer"]]
random.shuffle(answers)
view = TriviaView(question["correct_answer"], answers)
embed.add_field(name="Choose the correct answer:", value="Click one of the buttons below.", inline=False)
message = await ctx.send(embed=embed, view=view)
view.message = message # Reference for timeout handling
else:
await ctx.send("❗ Couldn't fetch a trivia question right now.")
# 4. Random Fact
@bot.command(name="fact", help="Get a random fact. Usage: !fact")
@is_registered()
async def fact(ctx):
random_fact = fetch_random_fact()
embed = discord.Embed(
title="🤔 Random Fact",
description=random_fact,
color=discord.Color.green()
)
await ctx.send(embed=embed)
# 5. Joke
@bot.command(name="joke", help="Get a random joke. Usage: !joke")
@is_registered()
async def joke(ctx):
joke_text = fetch_joke()
embed = discord.Embed(
title="😂 Here's a Joke for You!",
description=joke_text,
color=discord.Color.gold()
)
await ctx.send(embed=embed)
# 6. Quote
@bot.command(name="quote", help="Get a random inspirational quote. Usage: !quote")
@is_registered()
async def quote(ctx):
quote_text = fetch_quote()
embed = discord.Embed(
title="🌟 Inspirational Quote",
description=quote_text,
color=discord.Color.purple()
)
await ctx.send(embed=embed)
# 7. Dog Image
@bot.command(name="dog", help="Get a random dog image. Usage: !dog")
@is_registered()
async def dog(ctx):
image_url = fetch_random_dog_image()
if image_url:
embed = discord.Embed(
title="🐶 Here's a Cute Dog for You!",
color=discord.Color.brown()
).set_image(url=image_url)
await ctx.send(embed=embed)
else:
await ctx.send("❗ Couldn't fetch a dog image right now.")
# 8. Cat Image
@bot.command(name="cat", help="Get a random cat image. Usage: !cat")
@is_registered()
async def cat(ctx):
image_url = fetch_random_cat_image()
if image_url:
embed = discord.Embed(
title="🐱 Here's a Cute Cat for You!",
color=discord.Color.dark_purple()
).set_image(url=image_url)
await ctx.send(embed=embed)
else:
await ctx.send("❗ Couldn't fetch a cat image right now.")
# 9. Spell (Harry Potter)
@bot.command(name="spell", help="Get a random Harry Potter spell. Usage: !spell")
@is_registered()
async def spell(ctx):
spells = fetch_spells()
if spells:
spell = random.choice(spells)
embed = discord.Embed(
title=f"🔮 {spell['name']}",
description=spell['description'],
color=discord.Color.purple()
)
await ctx.send(embed=embed)
else:
await ctx.send("❗ Couldn't fetch a spell right now.")
# 10. Meal
@bot.command(name="meal", help="Get a random meal. Usage: !meal")
@is_registered()
async def meal(ctx):
meal = fetch_random_meal()
if meal:
embed = discord.Embed(
title=f"🍽️ {meal['strMeal']}",
description=f"Cuisine: {meal['strArea']}\nCategory: {meal['strCategory']}",
color=discord.Color.orange()
).set_image(url=meal['strMealThumb'])
await ctx.send(embed=embed)
else:
await ctx.send("❗ Couldn't fetch a meal right now.")
# 11. Reddit Post
@bot.command(name="reddit", help="Get a random post from a subreddit. Usage: !reddit <subreddit>")
@is_registered()
async def reddit(ctx, subreddit: str = None):
if not subreddit:
await ctx.send("❗ Please specify a subreddit. Usage: `!reddit <subreddit>`")
return
title, url = fetch_reddit_post(subreddit)
if title and url:
embed = discord.Embed(
title=title,
url=url,
color=discord.Color.red()
)
await ctx.send(embed=embed)
else:
await ctx.send("❗ Couldn't fetch a Reddit post. Please check the subreddit name.")
# 12. GitHub User Info
@bot.command(name="github", help="Get GitHub user information. Usage: !github <username>")
@is_registered()
async def github(ctx, username: str = None):
if not username:
await ctx.send("❗ Please specify a GitHub username. Usage: `!github <username>`")
return
result = fetch_github_user(username)
if result:
name, bio, repos, followers, following, avatar = result
embed = discord.Embed(
title=f"👤 GitHub User: {username}",
description=bio,
color=discord.Color.dark_blue()
)
embed.set_thumbnail(url=avatar)
embed.add_field(name="Name", value=name, inline=True)