From 0f1077778fce4f0bb25f5d603c1edb61c6b79d4d Mon Sep 17 00:00:00 2001 From: Kami Date: Fri, 14 Feb 2025 01:46:24 +0100 Subject: [PATCH] New `!funfact`/`!fun-fact` command - This command returns a random fun fact from a list of over 500 verified fun, surprising, or good-to-know facts, with unit conversions between metric and imperial. - Also started somewhat on the new Community Engagement Score (CES) system. - Currently not implemented to any working degree. - Will grant/deduct user scores depending on community engagement and actions overall. --- bots.py | 3 +- cmd_common/common_commands.py | 9 +- cmd_discord.py | 6 + cmd_twitch.py | 7 + dictionary/funfacts.json | 511 ++++++++++++++++++++++++++++++++++ modules/db.py | 195 +++++++++++++ 6 files changed, 729 insertions(+), 2 deletions(-) create mode 100644 dictionary/funfacts.json diff --git a/bots.py b/bots.py index d7f52ed..71a4979 100644 --- a/bots.py +++ b/bots.py @@ -53,7 +53,8 @@ async def main(): "Chatlog table": partial(db.ensure_chatlog_table, db_conn), "Howls table": partial(db.ensure_userhowls_table, db_conn), "Discord activity table": partial(db.ensure_discord_activity_table, db_conn), - "Account linking table": partial(db.ensure_link_codes_table, db_conn) + "Account linking table": partial(db.ensure_link_codes_table, db_conn), + "Community events table": partial(db.ensure_community_events_table, db_conn) } try: diff --git a/cmd_common/common_commands.py b/cmd_common/common_commands.py index a2dd965..5813ce3 100644 --- a/cmd_common/common_commands.py +++ b/cmd_common/common_commands.py @@ -3,6 +3,7 @@ import random import time from modules import utility import globals +import json from modules import db @@ -869,4 +870,10 @@ async def send_message(ctx, text): For discord.py: await ctx.send(text) For twitchio: await ctx.send(text) """ - await ctx.send(text) \ No newline at end of file + await ctx.send(text) + +# Common backend function to get a random fun fact +def get_fun_fact(): + with open('dictionary/funfacts.json', 'r') as f: + facts = json.load(f) + return random.choice(facts) \ No newline at end of file diff --git a/cmd_discord.py b/cmd_discord.py index bc478e9..820cd5d 100644 --- a/cmd_discord.py +++ b/cmd_discord.py @@ -33,6 +33,12 @@ def setup(bot): """ config_data = globals.load_config_file() + + @bot.command(name='funfact', aliases=['fun-fact']) + async def funfact_command(ctx): + fact = cc.get_fun_fact() + # Replies to the invoking user + await ctx.reply(fact) # ------------------------------------------------------------------------- diff --git a/cmd_twitch.py b/cmd_twitch.py index bd41220..1a26c31 100644 --- a/cmd_twitch.py +++ b/cmd_twitch.py @@ -13,6 +13,13 @@ def setup(bot, db_conn=None): This function is called to load/attach commands to the `bot`. We also attach the db_conn and log so the commands can use them. """ + + @commands.command(name='funfact', aliases=['fun-fact']) + async def funfact_command(self, ctx: commands.Context): + fact = cc.get_fun_fact() + # Replies to the invoking user by prefixing their name + await ctx.reply(fact) + @bot.command(name="greet") async def cmd_greet(ctx: commands.Context): result = cc.greet(ctx.author.display_name, "Twitch") diff --git a/dictionary/funfacts.json b/dictionary/funfacts.json new file mode 100644 index 0000000..511cea1 --- /dev/null +++ b/dictionary/funfacts.json @@ -0,0 +1,511 @@ +[ + "Bananas are berries, but strawberries are not.", + "Honey never spoils; archaeologists have found edible honey in ancient Egyptian tombs.", + "A day on Venus is longer than a year on Venus.", + "Octopuses have three hearts and blue blood.", + "There are more trees on Earth than stars in the Milky Way.", + "Some metals, like gallium, melt in your hand.", + "Wombat poop is cube-shaped.", + "The Eiffel Tower can be 15 cm taller during the summer.", + "A cloud can weigh more than 500.000kg (1 million pounds).", + "There's a species of jellyfish that is immortal.", + "Cows have best friends and get stressed when separated.", + "The heart of a blue whale is as big as a car.", + "A group of flamingos is called a 'flamboyance'.", + "The inventor of the frisbee was turned into a frisbee after he died.", + "A single strand of spaghetti is called a 'spaghetto'.", + "You can hear a blue whale's heartbeat from more than 3.2 km (2 miles) away.", + "Rats laugh when tickled.", + "Peanuts aren't nuts; they're legumes.", + "An adult human has fewer bones than a baby.", + "There's a basketball court on the top floor of the U.S. Supreme Court building.", + "A snail can sleep for three years.", + "There are more fake flamingos in the world than real ones.", + "Mosquitoes are attracted to people who just ate bananas.", + "Some turtles can breathe through their butts.", + "Cheetahs can't roar; they can only meow.", + "The inventor, Percy Spencer, of the microwave only received $2 for his discovery.", + "The majority of your brain is fat.", + "Hot water can freeze faster than cold water under certain conditions.", + "The unicorn is the national animal of Scotland.", + "Butterflies taste with their feet.", + "The first oranges weren't orange; they were green.", + "A bolt of lightning contains enough energy to toast 100,000 slices of bread.", + "A cloud can travel at speeds up to 97 km/h (60 mph).", + "Some cats are allergic to humans.", + "There are over 200 corpses of climbers on Mount Everest.", + "The oldest 'your mom' joke was discovered on a 3,500-year-old Babylonian tablet.", + "An apple, potato, and onion all taste the same if you eat them with your nose plugged.", + "A small child could swim through the veins of a blue whale.", + "A company in Taiwan makes dinnerware out of wheat, so you can eat your plate.", + "The human stomach gets a new lining every three to four days.", + "Some lipsticks contain fish scales.", + "There's a town in Norway called 'Hell' that freezes over every winter.", + "Almonds are a member of the peach family.", + "The longest place name in the world is 85 letters long.", + "The scientific name for brain freeze is 'sphenopalatine ganglioneuralgia'.", + "There's a museum in Sweden dedicated entirely to failures.", + "The first computer virus was created in 1983 as an experiment.", + "The shortest war in history was between Britain and Zanzibar on August 27, 1896, lasting just 38 to 45 minutes.", + "The inventor of the Pringles can, Fred Baur, is now buried in one.", + "A bolt of lightning can heat the air to five times hotter than the sun's surface.", + "Koala fingerprints are so similar to human fingerprints that they have been mistaken at crime scenes.", + "Sloths can hold their breath longer than dolphins.", + "The longest place name in the United States is 'Chargoggagoggmanchauggagoggchaubunagungamaugg'. It's commonly known as 'Webster Lake' in Webster, Massachusetts.", + "There's a species of fungus that turns ants into 'zombies'.", + "The human nose can detect over 1 trillion different scents.", + "A group of porcupines is called a 'prickle'.", + "Sea otters hold hands while sleeping so they don't drift apart.", + "The world's oldest toy is a stick.", + "The inventor of the modern zipper, Whitcomb Judson, initially failed to catch on with his invention.", + "A snail can have up to 25,000 teeth.", + "Polar bear skin is actually black.", + "The longest recorded flight of a chicken is 13 seconds.", + "The Twitter bird has a name: Larry.", + "The original London Bridge is now in Arizona.", + "A group of crows is called a 'murder'.", + "The average person walks the equivalent of five times around the world in their lifetime.", + "A 'jiffy' is an actual unit of time equal to 1/100th of a second.", + "The heart of a shrimp is located in its head.", + "In Switzerland, it is illegal to own just one guinea pig.", + "The mantis shrimp has the world's fastest punch, traveling at about 80 km/h (50 mph).", + "Bubble wrap was originally invented as wallpaper.", + "The first alarm clock could only ring at 4 a.m.", + "A hummingbird's heart can beat up to 1,260 times per minute.", + "There are more possible iterations of a game of chess than atoms in the known universe.", + "Some frogs can freeze without dying.", + "The plastic tips on shoelaces are called 'aglets'.", + "The word 'nerd' was first coined by Dr. Seuss in 'If I Ran the Zoo'.", + "A single strand of human hair can hold up to 100 grams.", + "A crocodile can't stick its tongue out.", + "The world's smallest reptile was discovered in 2021 and is just over 1.3 cm (0.5 inches) long.", + "Most of the dust in your home is made from dead skin cells.", + "Bananas glow blue under black lights.", + "A lightning strike can produce ozone, which is why the air smells fresh after a storm.", + "A day on Mercury lasts longer than its year.", + "There are more plastic flamingos in the world than real ones.", + "The world's deepest postbox is in Susami Bay, Japan, and is 10 meters underwater.", + "The longest wedding veil was longer than 63 football/soccer fields.", + "Humans share 50% of their DNA with bananas.", + "Olympic gold medals are mostly made of silver.", + "The tongue of a blue whale can weigh as much as an elephant.", + "Koalas sleep up to 22 hours a day.", + "The world's first website is still online.", + "The inventor of the lightbulb, Thomas Edison, once said he was afraid of the dark.", + "A cloud can hold up to a billion kilograms of water.", + "The record for the longest hiccuping spree is 68 years.", + "It takes glass over a million years to decompose.", + "The first VCR, created in 1956, was roughly the size of a piano.", + "Some turtles can live over 150 years.", + "The world's largest snowflake on record was 38cm (15 inches) wide.", + "An ostrich's eye is bigger than its brain.", + "The smell of freshly cut grass is actually a plant distress call.", + "Bees sometimes sting other bees.", + "The world's largest pizza was made in Rome and measured over 1,261 square meters.", + "The oldest piece of chewing gum is over 9,000 years old.", + "The word 'set' has the highest number of definitions in the English language.", + "Some frogs can freeze solid and then thaw out and hop away without harm.", + "The average human body has enough iron to make a small nail.", + "The planet Saturn could float in water because it is mostly made of gas.", + "A bee can fly around 10 km/h (6 mph).", + "The world's smallest mammal is the bumblebee bat.", + "Cows produce around 189,000 liters (200,000 quarts) of milk in their lifetime.", + "A piece of paper can typically be folded only 7 times.", + "The original name for a butterfly was 'flutterby'.", + "The longest word that can be typed using only the top row of a QWERTY keyboard is 'typewriter'.", + "An octopus can taste with its arms.", + "The inventor of the telephone, Alexander Graham Bell, never called his mother-in-law.", + "A giraffe can clean its ears with its 53 cm (21 inch) long tongue.", + "The lifespan of a single taste bud is about 10 days.", + "Humans can distinguish over a trillion different colors.", + "A single bolt of lightning contains enough energy to power a 100-watt light bulb for over 3 months.", + "The human nose can remember 50,000 different scents.", + "The world's fastest growing plant is the giant kelp.", + "Some cats have fewer toes on their back paws.", + "The world's oldest known wild bird is over 70 years old.", + "The unicorn is mentioned in the Bible as a symbol of strength.", + "The average person produces about 21.000 liters (22,000 quarts) of saliva in a lifetime.", + "The shortest commercial flight in the world lasts just 57 seconds.", + "There is a species of spider that mimics ants in appearance and behavior.", + "The world's largest grand piano was built by a 15-year-old in New Zealand.", + "In Japan, square watermelons are grown for easier stacking.", + "The first email was sent by Ray Tomlinson in 1971.", + "Lightning can strike the same place twice, and sometimes it does.", + "A day on Mercury lasts approximately 59 Earth days.", + "A snail can regenerate its eye stalks if they are damaged.", + "The longest continuous flight of a commercial airliner is over 18 hours.", + "Ants never sleep and they don't even have lungs.", + "The electric eel isn't really an eel, it's a knifefish.", + "The world's smallest book measures just 0.74 mm by 0.75 mm.", + "Some species of bamboo can grow over 89cm (35 inches) in a single day.", + "The giant squid has the largest eyes in the animal kingdom, measuring up to 25cm (10 inches).", + "Jellyfish are 95% water.", + "There are more bacteria in your mouth than there are people on Earth.", + "The world's largest desert isn't the Sahara, it's Antarctica.", + "Cleopatra lived closer in time to the Moon landing than to the construction of the Great Pyramid.", + "The tallest mountain in our solar system is Olympus Mons on Mars, nearly three times the height of Mount Everest.", + "Some fish can change their gender during their lifetime.", + "The combined weight of all ants on Earth is roughly equal to the combined weight of humans.", + "There is a museum dedicated solely to bad art in Massachusetts.", + "The original name of Google was 'Backrub'.", + "Wearing headphones for just an hour could increase the bacteria in your ear by 700 times.", + "Peacock feathers aren't actually colored, they're reflective structures that create iridescence.", + "The human brain uses 20% of the body's energy, even though it makes up only about 2% of the body's weight.", + "A group of ferrets is called a 'business'.", + "The first video ever uploaded on YouTube was 'Me at the zoo.'", + "If you shuffle a deck of cards, chances are that exact order has never been seen before in the history of the universe.", + "Walt Disney was cryogenically frozen, according to urban legend, though he was actually cremated.", + "The human heart creates enough pressure to squirt blood up to 30 feet.", + "Some plants can 'talk' to each other through underground fungal networks.", + "The longest English word without a vowel is 'rhythms'.", + "You can start a fire with ice by shaping it into a lens.", + "There are more stars in the universe than grains of sand on all the beaches on Earth.", + "Polar bears have black skin underneath their fur.", + "A hummingbird can fly backwards.", + "Kangaroos cannot walk backwards.", + "Sea cucumbers fight off predators by ejecting their internal organs.", + "A lightning bolt can travel at speeds up to 220,000 kilometers per hour.", + "The record for the longest time without sleep is 11 days.", + "A snail's trail is made of 98% water.", + "The world's largest flower, Rafflesia arnoldii, can reach up to 3 feet in diameter.", + "The oldest known animal was a quahog clam that lived for 507 years.", + "Caterpillars have more muscles than humans do.", + "The microwave was invented when a researcher's chocolate bar melted in his pocket near a radar tube.", + "There's a species of bat that emits sounds resembling a lion's roar.", + "The sound of a whip cracking is actually a mini sonic boom.", + "Some lizards can detach their tails to escape predators, and then grow them back.", + "Vending machines are more lethal than sharks, causing more deaths per year.", + "An adult human has about 100,000 hairs on their head.", + "The total length of blood vessels in the human body could circle the Earth 2.5 times.", + "Turtles have been around for over 200 million years, surviving the dinosaurs.", + "In ancient Rome, urine was commonly used as a cleaning agent for clothes.", + "One piece of space junk falls back to Earth every day.", + "The average person spends about 6 months of their lifetime waiting for red lights to turn green.", + "Cows have panoramic vision.", + "The plastic in credit cards can take up to 1,000 years to decompose.", + "In 2006, a man in Germany tried to trade a napkin for a car.", + "A lightning bolt can contain up to one billion volts of electricity.", + "The modern flush toilet was popularized by Thomas Crapper.", + "An average human produces enough saliva in a lifetime to fill two swimming pools.", + "The term 'piano' comes from the Italian 'pianoforte', meaning 'soft-loud'.", + "The Moon experiences moonquakes, similar to earthquakes on Earth.", + "A lightning bolt can be seen from over 150km (100 miles) away.", + "The world's largest hot dog was 203 feet long.", + "A cat has 32 muscles in each ear.", + "A hummingbird weighs less than a penny.", + "The average person will spend six months of their life in the bathroom.", + "The Bible is the most shoplifted book in the world.", + "Rabbits cannot vomit.", + "Sharks have existed longer than trees.", + "A hummingbird's egg weighs less than a dime.", + "It rains diamonds on Jupiter and Saturn.", + "The inventor of the chocolate chip cookie, Ruth Wakefield, sold the recipe for a dollar.", + "A lightning bolt can reach temperatures up to 30,000 Kelvin.", + "The average American eats around 18 acres of pizza in their lifetime.", + "The first product to have a barcode was Wrigley's gum.", + "In space, astronauts cannot cry because there's no gravity for tears to flow.", + "The Eiffel Tower was originally intended to be dismantled after 20 years.", + "An adult elephant's trunk contains over 40,000 muscles.", + "A day on Mars is approximately 24 hours and 39 minutes long.", + "The scent of rain, known as petrichor, is partly caused by bacteria called actinomycetes.", + "More people are allergic to cow's milk than to any other food.", + "Some species of ants form supercolonies spanning almost 6km (around 3.700 miles).", + "The cheetah, the fastest land animal, can accelerate from 0 to 60 mph in just 3 seconds.", + "Dolphins have been known to use tools, like sponges, to protect their snouts while foraging.", + "Despite popular belief, the Great Wall of China isn't visible from space with the naked eye.", + "In ancient Greece, throwing an apple at someone was considered a declaration of love.", + "There are more public libraries in the U.S. than there are McDonald's restaurants.", + "Bananas are naturally radioactive due to their high potassium content.", + "Shakespeare invented over 1,700 words that are now common in English.", + "A leap year occurs every 4 years, except in years divisible by 100 but not by 400.", + "In space there is no up or down; astronauts orient themselves relative to their spacecraft.", + "The world's largest recorded earthquake was a magnitude 9.5 in Chile in 1960.", + "The first known contraceptive was crocodile dung, used by ancient Egyptians.", + "M&M's stands for 'Mars & Murrie', the founders' last names.", + "The human body has enough carbon to fill 9,000 pencils.", + "The world's oldest pair of pants is over 3,000 years old.", + "Some birds, like the European robin, use Earth's magnetic field to navigate.", + "A newborn giraffe can stand within an hour of being born.", + "The shortest street in the world is Ebenezer Place in Scotland, measuring just 2.06 meters.", + "The Great Pyramid of Giza was the tallest man-made structure for over 3,800 years.", + "A single teaspoon of honey represents the life work of 12 bees.", + "The world's first roller coaster was built in Russia in the 17th century.", + "In Switzerland, it's illegal to mow your lawn on a Sunday.", + "The largest living structure on Earth is the Great Barrier Reef, visible from space.", + "The human brain can store up to 2.5 petabytes of information.", + "There's a fish called the 'Sarcastic Fringehead' known for its aggressive, gaping display.", + "A polar bear's fur is actually transparent, not white.", + "Some adult dragonflies live for as little as 24 hours.", + "There's a spot in the Pacific Ocean called Point Nemo, the furthest from any land.", + "Butterflies undergo a 4-stage life cycle: egg, larva, pupa, and adult.", + "A 'moment' in medieval times was defined as 90 seconds.", + "Sharks can detect a drop of blood in roughly 95 liters (25 gallons) of water.", + "A human sneeze can travel at speeds up to 161 km/h (100 mph).", + "Dolphins sleep with one eye open.", + "In Finland, speeding fines are calculated based on the offender's income.", + "Giraffes need only 5 to 30 minutes of sleep in a 24-hour period.", + "Some plants can survive for decades without sunlight by entering dormancy.", + "A full NASA spacesuit costs about $12 million.", + "Elephants are one of the few animals that can't jump.", + "The Sun makes up 99.86% of the mass in our solar system.", + "Starfish can regenerate lost arms, and sometimes a whole new starfish can grow from a single arm.", + "Bats are the only mammals capable of sustained flight.", + "The Great Wall of China spans around 20,921 km (over 13,000 miles).", + "The Greenland shark can live for over 400 years.", + "The color orange was named after the fruit, not the other way around.", + "A group of ravens is called an 'unkindness'.", + "In 1969, two computers at MIT were connected in a network that helped form the early Internet.", + "Some insects can survive in the vacuum of space for short periods.", + "Walt Disney's first Mickey Mouse cartoon was 'Steamboat Willie.'", + "A single lightning bolt can contain enough energy to power a city for a day.", + "The most expensive pizza in the world costs over $12,000 and takes 72 hours to prepare.", + "Venus rotates in the opposite direction to most planets in our solar system.", + "Cacti have evolved to store water in their tissues, allowing them to survive in deserts.", + "The first written recipe dates back over 4,000 years in ancient Mesopotamia.", + "The human body contains enough fat to produce over seven bars of soap.", + "The term 'robot' comes from the Czech word 'robota', meaning forced labor.", + "A lightning bolt can carry up to 100 million joules of energy.", + "The smallest country in the world is Vatican City.", + "In 1980, a Las Vegas hospital suspended workers for betting on when patients would die.", + "You can't hum while holding your nose.", + "Mice can sing, but their songs are too high-pitched for human ears.", + "There's an island in the Bahamas inhabited by swimming pigs.", + "Some metals, like sodium and potassium, react explosively with water.", + "The Guinness World Record for the most T-shirts worn at once is 257.", + "In ancient China, paper money was first used over 1,000 years ago.", + "There are more cells in the human body than there are stars in the Milky Way.", + "The coldest temperature ever recorded on Earth was -89.2°C (-128.6°F) in Antarctica.", + "Honeybees communicate by dancing in a figure-eight pattern.", + "The world's largest rubber band ball weighs 4,097 kg (over 9,000 lbs).", + "A single sneeze can produce up to 40,000 droplets.", + "In 2007, an Australian man built a car entirely out of Lego.", + "A group of flamingos is sometimes also called a 'stand'.", + "Some snakes can reproduce through parthenogenesis.", + "The first bicycle was invented in 1817.", + "Lightning strikes the Earth about 100 times per second.", + "The modern Olympic Games were revived in 1896.", + "There is a rare phenomenon known as 'ball lightning' that remains mysterious.", + "The speed of sound is about 343 meters per second in air.", + "In ancient Egypt, cats were revered and considered sacred.", + "A group of frogs is called an 'army'.", + "The first person convicted of speeding was clocked at around 13 km/h (8 mph).", + "Venus is the only planet that rotates clockwise.", + "The largest living animal is the blue whale.", + "A group of lions is called a 'pride'.", + "Some plants emit a faint glow in the dark, known as bioluminescence.", + "The average person blinks about 15–20 times per minute.", + "The original Xbox was released in 2001.", + "The first documented parachute jump was in 1797.", + "Some turtles breathe through their cloacas.", + "The Olympic torch relay tradition began at the 1936 Berlin Games.", + "There is a species of lizard that can squirt blood from its eyes as a defense mechanism.", + "Some sea snails have blue blood.", + "The oldest known written language is Sumerian.", + "In ancient Rome, purple clothing was reserved for royalty.", + "The Earth's magnetic field is shifting at about 15 km (9 miles) per year.", + "Some whale species can communicate over 250km (over 150 miles) on the surface. This increases to over 6.000km (over 3.700 miles) at certain depths.", + "In 1977, a radio signal from space, dubbed the 'Wow! signal', baffled scientists.", + "The average person walks about 112,650 km (70,000 miles) in their lifetime.", + "The human brain can generate about 20 watts of electrical power while awake.", + "America's first roller coaster was built in Coney Island in 1884.", + "There's a coral reef in the Red Sea that glows at night due to bioluminescent plankton.", + "The average human sheds about 600,000 particles of skin every hour.", + "The longest-running TV show is 'Guiding Light', which aired for 72 years.", + "Goldfish have a memory span of several months, not just three seconds.", + "Bats aren't blind; they rely on a combination of echolocation, vision, and smell to navigate.", + "Humans use virtually every part of their brain, the idea that we only use 10% is a myth.", + "Napoleon's height was average for his era; he wasn't unusually short.", + "Cracking your knuckles does not cause arthritis.", + "Vaccines do not cause autism.", + "Dogs see colors, primarily blues and yellows, even though their color range is more limited than humans'.", + "Hair and fingernails don't actually continue growing after death; skin dehydration makes them appear longer.", + "Sugar does not cause hyperactivity in children.", + "You don't swallow spiders in your sleep, this is a baseless myth.", + "Chameleons change color primarily for communication and regulating body temperature, not just for camouflage.", + "Swallowed gum passes through the digestive system in days, not years.", + "The rule of ‘8 glasses of water a day' is a myth, hydration needs vary based on many factors.", + "Lightning doesn't always strike the highest point; its path depends on complex atmospheric conditions.", + "Microwaves heat food by exciting water molecules, they do not make food radioactive or use harmful radiation.", + "Shaving hair does not cause it to grow back thicker or darker.", + "Humans have a keener sense of smell than commonly believed and can detect a vast array of odors.", + "Catching a cold isn't caused by being cold, the illness is due to viral infections.", + "Humans and dinosaurs never coexisted; dinosaurs went extinct about 65 million years before humans appeared.", + "Pure water is a poor conductor of electricity, the impurities (ions) in water make it conductive.", + "Humans have more than the traditional five senses; we also sense balance, temperature, pain, and more.", + "Ostriches do not bury their heads in the sand, the myth likely arose from their defensive behavior of lying low.", + "Duck quacks do echo; the idea that they don't is simply false.", + "Drinking alcohol doesn't actually warm you up, it causes blood vessels to dilate, leading to increased heat loss.", + "Mice have excellent memories and can be trained to remember complex tasks.", + "The full moon does not cause erratic human behavior, this popular belief isn't supported by solid scientific evidence.", + "Some sharks can actively pump water over their gills to breathe rather than needing constant motion.", + "Flight recorders (often called ‘black boxes') are painted bright orange to make them easier to locate after an accident.", + "A penny dropped from a great height is unlikely to kill a person because air resistance limits its terminal velocity.", + "Cats don't always land on their feet, while agile, falls can still result in injury.", + "The human brain continues to develop and change throughout life; neuroplasticity persists well beyond early adulthood.", + "Excess sugar alone doesn't directly cause diabetes, lifestyle factors and overall diet play major roles.", + "The ‘five-second rule' for dropped food is not scientifically valid; bacteria can contaminate food almost instantly.", + "Octopuses have a decentralized nervous system, with a central brain and mini-brains in each arm, allowing for complex, independent arm control.", + "Computers don't 'think' like humans, they perform rapid, specific calculations without any consciousness.", + "The idea that computer viruses come solely from rogue programmers is oversimplified; most malware exploits vulnerabilities in software.", + "Bananas naturally contain a small amount of the radioactive isotope potassium-40, proving that not all radioactivity is dangerous.", + "Microwave ovens heat food by exciting water molecules; they do not make food radioactive or alter its molecular structure in harmful ways.", + "Moore's Law, which predicted the doubling of transistors on a chip roughly every two years, is approaching physical limits as chip features reach the nanoscale.", + "Modern agriculture now relies heavily on technology and data analytics, contradicting the notion that farming is purely manual work.", + "Plant biotechnology, including gene editing like CRISPR, has revolutionized crop improvement, challenging the belief that genetics in agriculture is unchangeable.", + "While sci-fi often depicts robots as highly intelligent, most artificial intelligence today is specialized and lacks the general reasoning capabilities of humans.", + "Cloud computing isn't an abstract 'cloud' floating in space, it's backed by physical servers housed in data centers around the globe.", + "Nuclear reactors use controlled nuclear fission to safely generate energy, dispelling the myth that all nuclear processes are inherently catastrophic.", + "Everyday background radiation, from cosmic rays to radon, is a natural part of our environment and necessary for certain biological processes.", + "The internet is not a single, monolithic entity but a vast, decentralized network of interconnected systems and protocols.", + "Cryptocurrency networks like Bitcoin consume a lot of energy, yet the debate over their value and sustainability continues as technology evolves.", + "Machine learning algorithms require massive datasets and careful tuning, they don't 'learn' autonomously like the human brain.", + "Early computing devices, such as mechanical calculators and analog computers, predate modern digital computers by centuries.", + "Satellites and space probes are engineered for the vacuum and radiation of space, contradicting the idea that all technology is Earth-bound.", + "The electromagnetic spectrum includes many forms of energy, radio waves, microwaves, X-rays, and gamma rays, that are often misunderstood or unseen.", + "Cell phone signals are non-ionizing radiation, which means they don't carry enough energy to damage DNA, countering common fears about cancer.", + "Despite their complexity, even advanced computer chips operate using relatively simple physical principles governed by quantum mechanics.", + "The Green Revolution of the mid-20th century, which introduced high-yield hybrid seeds and chemical fertilizers, transformed agriculture and challenged traditional farming methods.", + "Controlled exposure to radiation in medical imaging (like X-rays and CT scans) is a powerful diagnostic tool, debunking the myth that all radiation is harmful.", + "Technological advances historically have disrupted certain jobs but ultimately create new industries and opportunities.", + "Scientific studies indicate that both organic and conventional produce offer similar nutritional benefits, challenging the assumption that organic always means healthier.", + "Everyday items like smoke detectors and luminous watch dials safely use small amounts of radioactive material, demonstrating that radioactivity isn't uniformly dangerous.", + "Quantum computing, based on superposition and entanglement, operates in ways that defy classical logic, contradicting everyday notions of how computers work.", + "Artificial intelligence systems are not infallible; they can reflect biases present in their training data and make errors, challenging the idea of AI as a perfect solution.", + "Solar panels can generate electricity on cloudy days too, contrary to the common belief that they only work in bright sunlight.", + "Rapid advancements in technology have dramatically reduced the cost of computing power over the decades, contradicting the notion that high-tech gadgets always have to be expensive.", + "The internet was originally designed as a resilient, decentralized network meant to withstand partial outages, rather than as a centralized, profit-driven platform.", + "Lightning can strike in clear weather, not just during a storm.", + "Plants communicate with each other by releasing volatile organic compounds that warn of pest attacks.", + "About 95% of the universe is made up of dark matter and dark energy, substances we cannot directly see.", + "Water expands when it freezes, which is why ice floats instead of sinking.", + "Every computer programming language is a human creation designed to instruct machines, not a form of natural thought.", + "If uncoiled, the DNA in your body could stretch from the sun to Pluto and back multiple times.", + "Earth's magnetic field shields us from harmful solar radiation.", + "It's not just the heat but the humidity that makes tropical summers feel oppressively sticky.", + "Astronauts can temporarily gain up to 5cm (2 inches) in height in space because their spinal discs expand without gravity's compression.", + "Crystals can grow faster in microgravity, which often produces unique structures not seen on Earth.", + "The pH of human blood is tightly regulated at about 7.4, regardless of what we eat.", + "A supernova explosion can briefly outshine an entire galaxy, defying our everyday sense of scale.", + "Much of the Internet's physical infrastructure still relies on decades-old copper wiring alongside modern fiber optics.", + "Quantum entanglement lets particles influence each other instantly, challenging our common-sense ideas of cause and effect.", + "Soil microbes play a huge role in sequestering carbon, which is vital for regulating Earth's climate.", + "Some bacteria thrive in extreme environments such as boiling acid or deep-sea vents, contrary to what we might expect about life.", + "Space isn't completely silent, electromagnetic vibrations can be translated into sound for scientific analysis.", + "Some studies suggest the human brain exhibits bursts of high activity during sleep, contradicting the idea that it ‘shuts off' at night.", + "Properly preserved digital storage media can last for centuries, challenging the notion that all digital data is short-lived.", + "Recycling electronic waste is far more complex than recycling paper or glass due to the variety of materials involved.", + "Engineers are developing advanced shielding techniques to protect spacecraft from high-radiation environments.", + "The rapid rise of renewable energy is driven as much by falling costs as by environmental concern.", + "Many modern computer algorithms draw inspiration from biological processes, such as neural networks that mimic brain function.", + "Today's organic farms frequently use cutting-edge technologies, drones, sensors, and data analytics, to monitor crops.", + "Even though cloud storage seems abstract, it relies on physical data centers distributed around the globe.", + "Radio telescopes, not just optical ones, provide critical insights into the composition of distant celestial objects.", + "Even the emptiest vacuum of space contains sparse particles and residual energy.", + "Rather than isolating us, technology often fosters global communities and unprecedented connectivity.", + "Advances in genetic engineering have improved crop nutrition and resistance, defying the idea that agricultural traits are fixed.", + "Certain bacteria can break down toxic waste into harmless substances, offering innovative solutions for environmental cleanup.", + "Solar flares can unexpectedly disrupt Earth's communications and power grids.", + "Many major computer security breaches occur because of simple human error, not just sophisticated hacking.", + "Modern agriculture uses precision farming techniques that tailor inputs like water and fertilizer to exact field conditions.", + "Radioactive isotopes are harnessed in medicine to both diagnose and treat various diseases.", + "A ‘perfect vacuum' is theoretical, there's always a residual presence of particles or energy even in space.", + "Breakthroughs in battery technology are making electric vehicles more practical than ever before.", + "Even on cloudy days, solar panels continue to produce electricity, albeit at a reduced efficiency.", + "Artificial intelligence systems depend on enormous datasets and careful tuning; they don't learn as humans do.", + "GPS satellites must correct for the effects of Einstein's relativity in order to provide accurate positioning.", + "The pace of technological change often outstrips our societal ability to adapt, challenging our expectations of progress.", + "Nanotechnology exploits the unique behaviors of materials at the nanoscale, defying everyday physics.", + "Superconductivity allows certain materials to conduct electricity with zero resistance when cooled sufficiently.", + "Modern cryptography relies on complex mathematical problems once deemed unsolvable.", + "The Internet of Things is revolutionizing agriculture by connecting sensors, weather stations, and equipment in real time.", + "Many conventional agricultural chemicals are being replaced by bio-based alternatives as environmental concerns grow.", + "Nuclear reactors operate under strict controls, proving that controlled fission can be a safe energy source.", + "Everyday background radiation, from cosmic rays to radon, is a natural part of our environment.", + "Cryptocurrency mining's heavy energy use has sparked debate over its sustainability and long-term viability.", + "Early computers, like the Z3 built by Konrad Zuse, show that digital technology has deep historical roots.", + "Satellites and space probes are meticulously engineered to withstand extreme conditions in space.", + "The electromagnetic spectrum is vast and includes radio waves, microwaves, X-rays, and gamma rays, many of which are invisible to us.", + "Cell phones emit non-ionizing radiation, which lacks the energy to damage DNA, a fact that contradicts common fears.", + "Even the most advanced microprocessors operate on fundamental quantum mechanics principles discovered over a century ago.", + "Modern studies reveal that both organic and conventional produce offer similar nutritional benefits.", + "Everyday items like smoke detectors contain minuscule amounts of radioactive material, safely used for practical purposes.", + "Quantum computers use superposition and entanglement to tackle problems beyond the reach of classical machines.", + "The term 'bug' in computing originated when an actual moth caused a malfunction in an early computer.", + "Semiconductor technology has transformed electronics, enabling devices that are far more powerful and compact than ever before.", + "Sand is the source of the silicon used in computer chips, turning a ubiquitous material into the backbone of modern technology.", + "Researchers have demonstrated that digital information can be encoded into DNA, potentially revolutionizing data storage.", + "Robots are increasingly collaborating with humans on production lines, combining machine precision with human creativity.", + "Genetically modified organisms undergo rigorous testing and regulation, countering many public misconceptions.", + "The first programmable computer, the Z3, was developed in 1941, predating many modern computing systems.", + "While the speed of light is constant in a vacuum, it slows when passing through materials like water or glass.", + "Deep-sea hydrothermal vents support entire ecosystems powered by chemosynthesis rather than sunlight.", + "Adaptive optics in modern telescopes correct for atmospheric distortion, yielding crystal-clear images of space.", + "Artificial neural networks mimic, but do not replicate, the complex processing of the human brain.", + "Many smartphones contain rare-earth elements that are critical to their high performance.", + "Data in computers is stored magnetically, optically, or electronically, each method with its own strengths.", + "Crop rotation, an ancient agricultural practice, is still proven to improve soil health today.", + "Ionizing radiation is naturally occurring and has been a constant factor throughout Earth's history.", + "Smart power grids now adjust energy distribution in real time to meet changing demands.", + "Fiber-optic technology has dramatically increased the speed and volume of global communications.", + "Space weather forecasting helps predict solar storms that could impact satellites and Earth-bound systems.", + "Industries are rapidly adopting 3D printing, which can reduce waste and streamline manufacturing processes.", + "Algorithms continue to evolve, enabling computers to analyze vast amounts of data more efficiently than ever.", + "The human brain's plasticity means that learning new skills can forge new neural connections even in later life.", + "Acoustic levitation uses powerful sound waves to suspend small objects in mid-air, a feat once thought impossible.", + "Satellite imagery is indispensable for tracking deforestation, urban sprawl, and other environmental changes.", + "Precision irrigation systems in agriculture conserve water by delivering exactly the right amount to each plant.", + "Bioinformatics, a merger of biology and computer science, is key to decoding vast genetic datasets.", + "Innovations in medical imaging, like MRI and PET scans, have revolutionized early disease detection.", + "Photolithography is a cornerstone of modern electronics, enabling the manufacture of ever-smaller microchips.", + "Blockchain technology is emerging as a tool for secure record-keeping beyond its role in cryptocurrencies.", + "Genetic improvements in crops have significantly reduced the need for chemical pesticides in modern farming.", + "Fusion energy research aims to harness a virtually limitless and clean energy source, despite current challenges.", + "Advancements in robotics now allow machines to perform incredibly delicate tasks, from surgery to micro-assembly.", + "Quantum cryptography promises theoretically unbreakable encryption using the principles of quantum mechanics.", + "There are materials that change color when exposed to different temperatures, pressures, or light conditions.", + "The behavior of electrons in semiconductors, arranged in distinct energy bands, is the foundation of modern electronics.", + "Sputnik's launch in 1957 marked the beginning of the space age and spurred decades of exploration.", + "Modern radar systems use radio waves to detect and track objects, essential for aviation and meteorology.", + "Precision agriculture leverages satellite data to optimize fertilizer use and water application.", + "Bioluminescence in organisms like certain plankton creates natural light shows in the ocean.", + "Moore's Law, though reaching its physical limits, has historically driven exponential growth in processing power.", + "Agricultural drones now routinely assess crop health and even apply targeted treatments over large fields.", + "Global data generation now reaches exabytes (1 000 000 000 GB) daily, underscoring the exponential growth of digital information.", + "Spectroscopy lets astronomers decipher the chemical makeup of stars by analyzing their light.", + "Ion propulsion systems accelerate ions to generate thrust, offering an alternative to conventional rockets.", + "Wearable technologies continuously monitor health metrics, providing insights once available only in clinics.", + "Space telescopes such as Hubble bypass atmospheric interference to deliver stunning views of the cosmos.", + "Vertical farming in urban settings grows crops in stacked layers, challenging traditional agricultural layouts.", + "Recent strides in AI have produced systems capable of generating human-like text, art, and even music.", + "Acoustics isn't just about sound in air, sound can travel through water, solids, and even plasma.", + "Cloud computing offers scalable, on-demand processing power that redefines the limits of traditional hardware.", + "Bioremediation employs microorganisms to degrade or transform environmental pollutants into non-toxic substances.", + "Deep learning breakthroughs have revolutionized image and speech recognition technologies.", + "Modern vehicles integrate sophisticated computer systems that manage everything from navigation to safety features.", + "The era of Big Data has enabled industries to analyze complex datasets, transforming business practices worldwide.", + "Nuclear magnetic resonance underpins MRI technology, allowing us to see inside the human body without surgery.", + "Graphene, an emerging material, boasts extraordinary strength and conductivity at just one atom thick.", + "Robotic process automation is increasingly handling repetitive tasks across sectors like finance and healthcare.", + "Self-driving cars combine sensor data, machine learning, and real-time processing to navigate complex environments.", + "High-energy particle accelerators probe the fundamental components of matter, expanding our understanding of physics.", + "Soil sensors in precision farming continuously measure moisture, pH, and nutrients to optimize plant growth.", + "Modern computers routinely use multicore processors to perform multiple tasks in parallel.", + "Breakthroughs in solar cell technology have led to panels that are both more efficient and less expensive.", + "3D bioprinting is emerging as a way to create living tissues for research and, eventually, organ transplants.", + "No-till farming practices help preserve soil structure and reduce erosion compared to conventional plowing.", + "Wireless charging uses electromagnetic fields to transfer energy, offering a cable-free way to power devices.", + "Extremophiles thriving in boiling acid or near-freezing conditions highlight the resilience of life.", + "The speed of data transfer in fiber-optic cables is determined by the refractive index of the glass.", + "Many modern agricultural operations now integrate both satellite and drone technologies for real-time monitoring.", + "Biotechnology has paved the way for pest-resistant crops that reduce the need for chemical interventions.", + "Superconductivity is not just a laboratory curiosity, it's applied in technologies like MRI machines and maglev trains.", + "Emerging quantum sensors can detect extremely subtle changes in magnetic and gravitational fields.", + "The evolution of microprocessors has been driven by relentless transistor miniaturization over the decades.", + "Agricultural research increasingly supports the idea that crop diversity can build resilience against climate change.", + "Nanomaterials exhibit properties that differ dramatically from their bulk counterparts, opening new technological frontiers.", + "The historical miniaturization of transistors has been a key driver in the rapid evolution of computing hardware.", + "Advances in image processing now enable computers to interpret and analyze visual data with remarkable precision.", + "Some nuclear power plants use naturally sourced water for cooling, challenging the notion that all require artificial systems.", + "Webster Lake, aka 'Chargoggagoggmanchauggagoggchaubunagungamaugg', can be translated to 'You fish on your side, I'll fish on my side, and no one shall fish in the middle.'" + ] + \ No newline at end of file diff --git a/modules/db.py b/modules/db.py index fe16186..1d80021 100644 --- a/modules/db.py +++ b/modules/db.py @@ -1061,3 +1061,198 @@ def merge_uuid_data(db_conn, old_uuid, new_uuid): globals.log(f"Deleted old UUID {old_uuid} from 'users' table ({rowcount} rows affected)", "INFO") globals.log(f"UUID merge complete: {old_uuid} -> {new_uuid}", "INFO") + +def ensure_community_events_table(db_conn): + """ + Checks if 'community_events' table exists. If not, attempts to create it. + Raises an Exception or logs errors if creation fails. + """ + # 1) Determine if DB is sqlite or MariaDB/MySQL + is_sqlite = "sqlite3" in str(type(db_conn)).lower() + + # 2) Check for existence + if is_sqlite: + check_sql = """ + SELECT name + FROM sqlite_master + WHERE type='table' + AND name='community_events' + """ + else: + check_sql = """ + SELECT table_name + FROM information_schema.tables + WHERE table_name = 'community_events' + AND table_schema = DATABASE() + """ + from modules.db import run_db_operation + rows = run_db_operation(db_conn, "read", check_sql) + if rows and rows[0] and rows[0][0]: + globals.log("Table 'community_events' already exists, skipping creation.", "DEBUG") + return + + globals.log("Table 'community_events' does not exist; creating now...", "DEBUG") + if is_sqlite: + create_table_sql = """ + CREATE TABLE community_events ( + EVENT_ID INTEGER PRIMARY KEY AUTOINCREMENT, + EVENT_PLATFORM TEXT NOT NULL, + EVENT_TYPE TEXT NOT NULL, + EVENT_DETAILS TEXT, + EVENT_USER TEXT NOT NULL, + DATETIME TEXT NOT NULL, + EVENT_EXTRAS TEXT + ) + """ + else: + create_table_sql = """ + CREATE TABLE community_events ( + EVENT_ID INT PRIMARY KEY AUTO_INCREMENT, + EVENT_PLATFORM VARCHAR(50) NOT NULL, + EVENT_TYPE VARCHAR(100) NOT NULL, + EVENT_DETAILS TEXT, + EVENT_USER VARCHAR(100) NOT NULL, + DATETIME DATETIME DEFAULT CURRENT_TIMESTAMP, + EVENT_EXTRAS TEXT + ) + """ + result = run_db_operation(db_conn, "write", create_table_sql) + if result is None: + error_msg = "Failed to create 'community_events' table!" + globals.log(error_msg, "CRITICAL") + raise RuntimeError(error_msg) + globals.log("Successfully created table 'community_events'.", "DEBUG") + + +async def handle_community_event(db_conn, is_discord, ctx, args): + """ + Handles community event commands. + + Accepted subcommands (args[0] if provided): + - add [event_details [|| event_extras]] + -> Logs a new event. + - info + -> Retrieves detailed information for a given event. + - list [limit] + -> Lists recent events (default limit 5 if not specified). + - search + -> Searches events (by EVENT_TYPE or EVENT_DETAILS). + + If no arguments are provided, defaults to listing recent events. + """ + from modules import db # Assumes your db module is available + if len(args) == 0: + args = ["list"] + + sub = args[0].lower() + + if sub == "add": + if len(args) < 2: + return "Please provide the event type after 'add'." + event_type = args[1] + # Concatenate remaining args as event details (if any) + event_details = " ".join(args[2:]).strip() if len(args) > 2 else None + + # Optional: If you want to support extras, you might separate event_details and extras using "||" + event_extras = None + if event_details and "||" in event_details: + parts = event_details.split("||", 1) + event_details = parts[0].strip() + event_extras = parts[1].strip() + + platform = "Discord" if is_discord else "Twitch" + user_id = str(ctx.author.id) + # Lookup user data to get UUID (similar to your quote logic) + user_data = db.lookup_user(db_conn, identifier=user_id, identifier_type=f"{platform.lower()}_user_id") + if not user_data: + globals.log(f"Could not find UUID for user {ctx.author.name} ({user_id}) on {platform}.", "ERROR") + return "Could not log event: user data missing." + user_uuid = user_data["UUID"] + + # Insert new event. Use appropriate parameter placeholders. + if "sqlite3" in str(type(db_conn)).lower(): + insert_sql = """ + INSERT INTO community_events + (EVENT_PLATFORM, EVENT_TYPE, EVENT_DETAILS, EVENT_USER, DATETIME, EVENT_EXTRAS) + VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP, ?) + """ + else: + insert_sql = """ + INSERT INTO community_events + (EVENT_PLATFORM, EVENT_TYPE, EVENT_DETAILS, EVENT_USER, DATETIME, EVENT_EXTRAS) + VALUES (%s, %s, %s, %s, CURRENT_TIMESTAMP, %s) + """ + params = (platform, event_type, event_details, user_uuid, event_extras) + result = db.run_db_operation(db_conn, "write", insert_sql, params) + if result is not None: + globals.log(f"New event added: {event_type} by {ctx.author.name}", "DEBUG") + return f"Successfully logged event: {event_type}" + else: + return "Failed to log event." + + elif sub == "info": + if len(args) < 2 or not args[1].isdigit(): + return "Please specify a valid event ID." + event_id = int(args[1]) + select_sql = "SELECT * FROM community_events WHERE EVENT_ID = ?" + if "sqlite3" not in str(type(db_conn)).lower(): + select_sql = "SELECT * FROM community_events WHERE EVENT_ID = %s" + rows = db.run_db_operation(db_conn, "read", select_sql, (event_id,)) + if not rows: + return f"No event found with ID {event_id}." + row = rows[0] + # row indices: 0: EVENT_ID, 1: EVENT_PLATFORM, 2: EVENT_TYPE, 3: EVENT_DETAILS, + # 4: EVENT_USER, 5: DATETIME, 6: EVENT_EXTRAS + resp = ( + f"Event #{row[0]}:\n" + f"Platform: {row[1]}\n" + f"Type: {row[2]}\n" + f"Details: {row[3] or 'N/A'}\n" + f"User UUID: {row[4]}\n" + f"Datetime: {row[5]}\n" + f"Extras: {row[6] or 'N/A'}" + ) + return resp + + elif sub == "list": + # Optional limit argument (default 5) + limit = 5 + if len(args) >= 2 and args[1].isdigit(): + limit = int(args[1]) + select_sql = f"SELECT * FROM community_events ORDER BY DATETIME DESC LIMIT {limit}" + rows = db.run_db_operation(db_conn, "read", select_sql) + if not rows: + return "No events logged yet." + resp_lines = [] + for row in rows: + # Display basic info: ID, Type, Platform, Datetime + resp_lines.append(f"#{row[0]}: {row[2]} on {row[1]} at {row[5]}") + return "\n".join(resp_lines) + + elif sub == "search": + if len(args) < 2: + return "Please provide keywords to search for." + keywords = " ".join(args[1:]) + like_pattern = f"%{keywords}%" + search_sql = """ + SELECT * FROM community_events + WHERE EVENT_TYPE LIKE ? OR EVENT_DETAILS LIKE ? + ORDER BY DATETIME DESC LIMIT 5 + """ + if "sqlite3" not in str(type(db_conn)).lower(): + search_sql = """ + SELECT * FROM community_events + WHERE EVENT_TYPE LIKE %s OR EVENT_DETAILS LIKE %s + ORDER BY DATETIME DESC LIMIT 5 + """ + rows = db.run_db_operation(db_conn, "read", search_sql, (like_pattern, like_pattern)) + if not rows: + return "No matching events found." + resp_lines = [] + for row in rows: + resp_lines.append(f"#{row[0]}: {row[2]} on {row[1]} at {row[5]}") + return "\n".join(resp_lines) + + else: + # Unknown subcommand; default to listing recent events. + return await handle_community_event_command(db_conn, is_discord, ctx, ["list"])