From 898e9c2f14d7bd15f909336a60cb2c20ab44818d Mon Sep 17 00:00:00 2001 From: georgeamccarthy <> Date: Fri, 11 Jun 2021 11:48:37 +0000 Subject: [PATCH 01/20] Correct token code. Still not working, likely a server bug. --- mentalHealthBot.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/mentalHealthBot.py b/mentalHealthBot.py index cdd876b..f45b8b3 100644 --- a/mentalHealthBot.py +++ b/mentalHealthBot.py @@ -15,9 +15,14 @@ import random from keepalive import keepalive +""" +# DEBUG +for key in os.environ: + print (key) +""" + # enter token for the server -TOKEN = os.getenv('DISCORD_TOKEN') -# enter application id +TOKEN = os.environ['DISCORD_TOKEN'] # client = commands.Bot(command_prefix='.') From 8b78eee7eb090bb072753c622b816a6918457fb5 Mon Sep 17 00:00:00 2001 From: georgeamccarthy <> Date: Fri, 11 Jun 2021 11:59:05 +0000 Subject: [PATCH 02/20] Updated requirements. Server token working (needed to not use venv). --- mentalHealthBot.py | 6 --- requirements.txt | 132 ++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 131 insertions(+), 7 deletions(-) diff --git a/mentalHealthBot.py b/mentalHealthBot.py index f45b8b3..9e58d91 100644 --- a/mentalHealthBot.py +++ b/mentalHealthBot.py @@ -15,12 +15,6 @@ import random from keepalive import keepalive -""" -# DEBUG -for key in os.environ: - print (key) -""" - # enter token for the server TOKEN = os.environ['DISCORD_TOKEN'] diff --git a/requirements.txt b/requirements.txt index 0b1fd46..4429143 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,12 +1,142 @@ +absl-py==0.12.0 aiohttp==3.7.4.post0 +antlr4-python3-runtime==4.9.2 +astunparse==1.6.3 async-timeout==3.0.1 attrs==21.2.0 +CacheControl==0.12.6 +cachetools==4.2.2 +cachy==0.3.0 +Cerberus==1.3.4 +certifi==2020.12.5 +cffi==1.14.5 chardet==4.0.0 +cleo==0.7.6 +click==8.0.1 +clikit==0.4.3 +cryptography==3.4.7 +cs50==6.0.4 +cycler==0.10.0 +debugpy==1.2.1 +dephell==0.8.3 +dephell-archive==0.1.7 +dephell-argparse==0.1.3 +dephell-changelogs==0.0.1 +dephell-discover==0.2.10 +dephell-licenses==0.1.7 +dephell-links==0.1.5 +dephell-markers==1.0.3 +dephell-pythons==0.1.15 +dephell-setuptools==0.2.4 +dephell-shells==0.1.5 +dephell-specifier==0.2.2 +dephell-venvs==0.1.18 +dephell-versioning==0.1.2 discord==1.0.1 discord.py==1.7.2 -idna==3.2 +docopt==0.6.2 +docutils==0.17.1 +Flask==2.0.1 +funcsigs==1.0.2 +future==0.18.2 +gast==0.3.3 +glfw==2.1.0 +google-api-core==1.30.0 +google-api-python-client==2.8.0 +google-auth==1.30.1 +google-auth-httplib2==0.1.0 +google-auth-oauthlib==0.4.4 +google-pasta==0.2.0 +googleapis-common-protos==1.53.0 +greenlet==1.1.0 +grpcio==1.38.0 +h5py==2.10.0 +html5lib==1.1 +httplib2==0.19.1 +idna==2.10 +importlib-metadata==3.10.1 +itsdangerous==2.0.1 +jedi==0.15.2 +jeepney==0.6.0 +Jinja2==3.0.1 +joblib==1.0.1 +jsonschema==3.2.0 +Keras-Preprocessing==1.1.2 +keyring==20.0.1 +kiwisolver==1.3.1 +lockfile==0.12.2 +m2r==0.2.1 +Markdown==3.3.4 +MarkupSafe==2.0.1 +matplotlib==3.4.2 +mistune==0.8.4 +msgpack==1.0.2 multidict==5.1.0 +nltk==3.6.2 +numpy==1.20.3 +oauthlib==3.1.0 +opt-einsum==3.3.0 +packaging==20.9 +parso==0.5.2 +pastel==0.2.1 +pexpect==4.8.0 +Pillow==8.2.0 +pipreqs-amasad==0.4.10 +pkginfo==1.7.0 +pluggy==0.13.1 +poetry==1.0.5 +protobuf==3.17.1 +ptyprocess==0.7.0 +pyasn1==0.4.8 +pyasn1-modules==0.2.8 +pycparser==2.20 +pyflakes==2.1.1 +pygame==2.0.1 +pylev==1.3.0 +PyOpenGL==3.1.5 +pyparsing==2.4.7 +pyquil==1.9.0 +pyrsistent==0.14.11 +python-dateutil==2.8.1 python-dotenv==0.17.1 +python-jsonrpc-server==0.3.2 +python-language-server==0.31.10 +pytz==2021.1 +pyxel==1.0.1 +referenceqvm==0.3 +regex==2021.4.4 +replit==3.1.0 requests==2.25.1 +requests-oauthlib==1.3.0 +requests-toolbelt==0.8.0 +rope==0.18.0 +rsa==4.7.2 +ruamel.yaml==0.17.4 +ruamel.yaml.clib==0.2.2 +scipy==1.4.1 +SecretStorage==3.3.1 +shellingham==1.4.0 +six==1.16.0 +sounddevice==0.4.1 +SQLAlchemy==1.4.15 +sqlparse==0.4.1 +tensorboard==2.2.2 +tensorboard-plugin-wit==1.8.0 +tensorflow-cpu==2.2.0 +tensorflow-estimator==2.2.0 +termcolor==1.1.0 +toml==0.10.2 +tomlkit==0.5.11 +tqdm==4.61.0 typing-extensions==3.10.0.0 +ujson==1.35 +uritemplate==3.0.1 +urllib3==1.26.5 +webencodings==0.5.1 +Werkzeug==2.0.1 +wrapt==1.12.1 +yapf==0.31.0 +yarg==0.1.9 yarl==1.6.3 +yaspin==2.0.0 +zipp==3.4.1 From 9f307d4a555e79718757f1b958325c2d43c693e7 Mon Sep 17 00:00:00 2001 From: georgeamccarthy <> Date: Fri, 11 Jun 2021 12:09:08 +0000 Subject: [PATCH 03/20] Correct requirements --- mentalHealthBot.py | 6 ------ requirements.txt | 7 +++++++ 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/mentalHealthBot.py b/mentalHealthBot.py index f45b8b3..9e58d91 100644 --- a/mentalHealthBot.py +++ b/mentalHealthBot.py @@ -15,12 +15,6 @@ import random from keepalive import keepalive -""" -# DEBUG -for key in os.environ: - print (key) -""" - # enter token for the server TOKEN = os.environ['DISCORD_TOKEN'] diff --git a/requirements.txt b/requirements.txt index 0b1fd46..a127187 100644 --- a/requirements.txt +++ b/requirements.txt @@ -10,3 +10,10 @@ python-dotenv==0.17.1 requests==2.25.1 typing-extensions==3.10.0.0 yarl==1.6.3 +google-api-core==1.30.0 +google-api-python-client==2.8.0 +google-auth==1.30.1 +google-auth-httplib2==0.1.0 +google-auth-oauthlib==0.4.4 +google-pasta==0.2.0 +googleapis-common-protos==1.53.0 \ No newline at end of file From 7323d902b293bd243c2ca8567a8bbb71318148b8 Mon Sep 17 00:00:00 2001 From: "George A. McCarthy" <65653499+georgeamccarthy@users.noreply.github.com> Date: Fri, 11 Jun 2021 13:23:06 +0100 Subject: [PATCH 04/20] Fix server token and update requirements. (#13) * Correct token code. Still not working, likely a server bug. * Updated requirements. Server token working (needed to not use venv). * Correct requirements Co-authored-by: georgeamccarthy <> --- mentalHealthBot.py | 3 +-- requirements.txt | 30 ++++++++++++++++++++++-------- 2 files changed, 23 insertions(+), 10 deletions(-) diff --git a/mentalHealthBot.py b/mentalHealthBot.py index cdd876b..9e58d91 100644 --- a/mentalHealthBot.py +++ b/mentalHealthBot.py @@ -16,8 +16,7 @@ from keepalive import keepalive # enter token for the server -TOKEN = os.getenv('DISCORD_TOKEN') -# enter application id +TOKEN = os.environ['DISCORD_TOKEN'] # client = commands.Bot(command_prefix='.') diff --git a/requirements.txt b/requirements.txt index 0b1fd46..882591c 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,12 +1,26 @@ +absl-py==0.12.0 aiohttp==3.7.4.post0 +antlr4-python3-runtime==4.9.2 +astunparse==1.6.3 async-timeout==3.0.1 attrs==21.2.0 +CacheControl==0.12.6 +cachetools==4.2.2 +cachy==0.3.0 +Cerberus==1.3.4 +certifi==2020.12.5 +cffi==1.14.5 chardet==4.0.0 -discord==1.0.1 -discord.py==1.7.2 -idna==3.2 -multidict==5.1.0 -python-dotenv==0.17.1 -requests==2.25.1 -typing-extensions==3.10.0.0 -yarl==1.6.3 +cleo==0.7.6 +click==8.0.1 +clikit==0.4.3 +cryptography==3.4.7 +cs50==6.0.4 +cycler==0.10.0 +google-api-core==1.30.0 +google-api-python-client==2.8.0 +google-auth==1.30.1 +google-auth-httplib2==0.1.0 +google-auth-oauthlib==0.4.4 +google-pasta==0.2.0 +googleapis-common-protos==1.53.0 \ No newline at end of file From 76013d70ee9c314372b5c871df980d0e72ef8c35 Mon Sep 17 00:00:00 2001 From: georgeamccarthy <> Date: Fri, 11 Jun 2021 12:27:59 +0000 Subject: [PATCH 05/20] Fix requirements --- requirements.txt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/requirements.txt b/requirements.txt index 882591c..86be19a 100644 --- a/requirements.txt +++ b/requirements.txt @@ -17,6 +17,8 @@ clikit==0.4.3 cryptography==3.4.7 cs50==6.0.4 cycler==0.10.0 +discord==1.0.1 +discord.py==1.7.2 google-api-core==1.30.0 google-api-python-client==2.8.0 google-auth==1.30.1 From 511adb52d5429a9e7dd2b0a69ae6da90b240ba6c Mon Sep 17 00:00:00 2001 From: georgeamccarthy <> Date: Fri, 11 Jun 2021 12:31:13 +0000 Subject: [PATCH 06/20] Fix requirements --- requirements.txt | 23 +++++++---------------- 1 file changed, 7 insertions(+), 16 deletions(-) diff --git a/requirements.txt b/requirements.txt index 86be19a..844ab00 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,22 +1,7 @@ -absl-py==0.12.0 aiohttp==3.7.4.post0 -antlr4-python3-runtime==4.9.2 -astunparse==1.6.3 async-timeout==3.0.1 attrs==21.2.0 -CacheControl==0.12.6 -cachetools==4.2.2 -cachy==0.3.0 -Cerberus==1.3.4 -certifi==2020.12.5 -cffi==1.14.5 chardet==4.0.0 -cleo==0.7.6 -click==8.0.1 -clikit==0.4.3 -cryptography==3.4.7 -cs50==6.0.4 -cycler==0.10.0 discord==1.0.1 discord.py==1.7.2 google-api-core==1.30.0 @@ -25,4 +10,10 @@ google-auth==1.30.1 google-auth-httplib2==0.1.0 google-auth-oauthlib==0.4.4 google-pasta==0.2.0 -googleapis-common-protos==1.53.0 \ No newline at end of file +googleapis-common-protos==1.53.0 +idna==3.2 +multidict==5.1.0 +python-dotenv==0.17.1 +requests==2.25.1 +typing-extensions==3.10.0.0 +yarl==1.6.3 \ No newline at end of file From 148d6fe1bb11d1789d5dca943970bece567375b7 Mon Sep 17 00:00:00 2001 From: SaurabhAgarwala Date: Fri, 11 Jun 2021 19:15:42 +0530 Subject: [PATCH 07/20] Add help text to commands --- .gitignore | 1 + mentalHealthBot.py => FellowBot.py | 36 +++++++++++++----------------- bot.py => trialBot.py | 0 3 files changed, 17 insertions(+), 20 deletions(-) rename mentalHealthBot.py => FellowBot.py (88%) rename bot.py => trialBot.py (100%) diff --git a/.gitignore b/.gitignore index cda2e01..e1ff76f 100644 --- a/.gitignore +++ b/.gitignore @@ -134,3 +134,4 @@ google-calendar-quickstart.py credentials.json token.json ok.json +faq.json diff --git a/mentalHealthBot.py b/FellowBot.py similarity index 88% rename from mentalHealthBot.py rename to FellowBot.py index 9e58d91..17a39af 100644 --- a/mentalHealthBot.py +++ b/FellowBot.py @@ -9,22 +9,18 @@ import json import os -import discord import requests from discord.ext import commands import random from keepalive import keepalive +from discord.ext import commands # enter token for the server -TOKEN = os.environ['DISCORD_TOKEN'] - -# client = commands.Bot(command_prefix='.') +# TOKEN = os.environ['DISCORD_TOKEN'] # to use in repl -import discord -from discord.ext import commands -# from dotenv import load_dotenv -# load_dotenv() -# TOKEN = os.getenv('DISCORD_TOKEN') +from dotenv import load_dotenv +load_dotenv() +TOKEN = os.getenv('DISCORD_TOKEN') # for dev purpose # If modifying these scopes, delete the file token.json. SCOPES = ['https://www.googleapis.com/auth/calendar.readonly'] @@ -33,7 +29,7 @@ # ---------------------BOT COMMAND bot = commands.Bot(command_prefix='!') # ---------------------WEB SCRAPING -scraping = open("ok.json", encoding="UTF-8") +scraping = open("faq.json", encoding="UTF-8") scraped = json.load(scraping) # ----------------FOR HELPLINE helplines = ["Family Violence Prevention Center 1-800-313-1310", @@ -44,7 +40,7 @@ "GriefShare 1-800-395-5755", "Suicide Hotline 1-800-SUICIDE (784-2433)"] -@bot.command(aliases=['event', 'nextevent', 'nextevents', 'upcomingevent', 'upcomingevents'], help='Get a list of the ongoing and upcoming events of the pod') +@bot.command(aliases=['event', 'nextevent', 'nextevents', 'upcomingevent', 'upcomingevents'], help='Get a list of the ongoing and upcoming events of the pod. Enter the count of events to retrieve following the command. It\'s default value is 1.') async def events(ctx, count='1'): creds = None # The file token.json stores the user's access and refresh tokens, and is @@ -106,7 +102,7 @@ async def events(ctx, count='1'): # await ctx.send(event['description']) -@bot.command(name='faq', help='Searches the FAQ for the most relevant section corresponding to the provided keyword.') +@bot.command(name='faq', help='Searches the FAQ for the most relevant section corresponding to the provided keyword. List of keywords: MLHintro, pod, MLHevents, discord, zoom, feedback, feedback, hackathonrules, hackjudge, hackdemo, attendance, expectations, help') async def faq(ctx, keyword): for i in scraped["intents"]: if(keyword==i["tag"]): @@ -117,37 +113,37 @@ async def faq(ctx, keyword): await ctx.send(response) -@bot.command(aliases=['al']) +@bot.command(aliases=['al'], help="Get all helpline numbers related to mental health") async def all(ctx): for i in helplines: res = i await ctx.send(res) -@bot.command(aliases=['depression']) +@bot.command(aliases=['depression'], help="Get helpline number to tackle depression and suicidal thoughts") async def suicide(ctx): await ctx.send(helplines[6]) -@bot.command(aliases=['violenT']) +@bot.command(aliases=['violent'], help="Get helpline number to tackle violence") async def violence(ctx): await ctx.send(helplines[0]) -@bot.command(aliases=['drugs']) +@bot.command(aliases=['drugs'], help="Get helpline number to tackle drug addiction") async def drugabuse(ctx): await ctx.send(helplines[2]) -@bot.command(aliases=['assault']) +@bot.command(aliases=['assault'], help="Get helpline number to tackle assaults") async def sexualAssault(ctx): await ctx.send(helplines[1]) -@bot.command(aliases=['ILLNESS']) +@bot.command(aliases=['ILLNESS'], help="Get helpline number to tackle illness") async def cancer(ctx): await ctx.send(helplines[3]) -@bot.command(aliases=['grie']) +@bot.command(aliases=['sorrow'], help="Get helpline number to tackle grief") async def grief(ctx): await ctx.send(helplines[5]) -@bot.command(aliases=['eating']) +@bot.command(aliases=['eating'], help="Get helpline number to tackle eating disorder") async def eatingdisorder(ctx): await ctx.send(helplines[4]) diff --git a/bot.py b/trialBot.py similarity index 100% rename from bot.py rename to trialBot.py From 3b750273d7a16f97c387600830d540393e07f7ea Mon Sep 17 00:00:00 2001 From: SaurabhAgarwala Date: Fri, 11 Jun 2021 19:33:43 +0530 Subject: [PATCH 08/20] Update help text of FAQs --- FellowBot.py | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/FellowBot.py b/FellowBot.py index 17a39af..1195b7b 100644 --- a/FellowBot.py +++ b/FellowBot.py @@ -102,7 +102,22 @@ async def events(ctx, count='1'): # await ctx.send(event['description']) -@bot.command(name='faq', help='Searches the FAQ for the most relevant section corresponding to the provided keyword. List of keywords: MLHintro, pod, MLHevents, discord, zoom, feedback, feedback, hackathonrules, hackjudge, hackdemo, attendance, expectations, help') +@bot.command(name='faq', help="\ + Searches the FAQ for the most relevant section corresponding to the provided keyword. List of keywords: \ + - πŸ˜„ **MLHintro** - For in depth introduction to MLH fellowship. \ + - 🌲 **MLHevents**- What are MLH events? Know everything about them. \ + - πŸš‚ **pods** - What are pods? Know everything here \ + - πŸ“± **discord** -How to use discord and which channel serves what purpose \ + - πŸ“ž **zoom**- What is zoom used for? \ + - πŸ“’ **feedback** - What is feedback in MLH? \ + - ⏰ **remote** - How to work remotely and give your 100% in MLH. \ + - πŸ“ **hackathonrules** - Rules for hackathons \ + - πŸ₯‡ **hackjudge** - How do judges make a decision for hackathon winner? What is taken into consideration? \ + - πŸ’― **hackdemo** - How to prepare a good demo for hackathon? \ + - πŸ™‹ **attendance** - What is the importance of attendance in MLH and how is it monitored?\ + - πŸ’ **expectations** - What MLH expects from you as fellows\ + - ⛑️ **help** - Facing problems in MLH? Reach out to us\ +") async def faq(ctx, keyword): for i in scraped["intents"]: if(keyword==i["tag"]): From ddcca4befd19f19b529a34f88dda0ca3b80ee65e Mon Sep 17 00:00:00 2001 From: "George A. McCarthy" <65653499+georgeamccarthy@users.noreply.github.com> Date: Fri, 11 Jun 2021 16:00:07 +0100 Subject: [PATCH 09/20] Update README.md --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index 84859d2..a0ec727 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,3 @@ -# FellowBot # FellowBot πŸ€– ### MLH kick-off hackathon Project - FellowBuddy Discord Bot From e91326039ea31db4d04c634a306b308741977508 Mon Sep 17 00:00:00 2001 From: Saurabh Agarwala Date: Fri, 11 Jun 2021 22:35:30 +0530 Subject: [PATCH 10/20] Update README.md Solves #18 --- README.md | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index a0ec727..d3f41a6 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # FellowBot πŸ€– ### MLH kick-off hackathon Project - FellowBuddy Discord Bot - +#### Check out the FellowBot website [here](https://mlh-fellowship.github.io/FellowBot/) ## **Hi there ! :wave:** ![Cover](Fb.gif) @@ -25,6 +25,7 @@ We understand how sometimes life in particular can be difficult and since we are The project is a discord bot with the following features: - 🧠 Mental health support - We understand how stressful it can be to manage everything and keep a positive attitude. Come talk to FellowBot about stress, life and unwanted feelings and it will help you!. Have difficulty managinng time? It will recommend you techniques to stay focused. Having a bad day? It will tell you a joke too!. Want motivation? Well, FellowBot will send you an inspiational quote too!. - ✨ Handbook scraping - We understand that you might not remember every page of the handbook but we also agree it is your best friend in this fellowship!. So, need to search for a particular page? Just type in a relevant keyword from our list of keywords and have the information directly in your discord. Say goodbye to searches again! +- πŸ“… Next events - There are many events which fellows in MLH have to attend. Spending most of their time in Discord, there must be a way to get it directly there. Voila! Just use our FellowBot to get a list of a few ongoing/upcoming events. ## Techstack @@ -33,6 +34,8 @@ The project is a discord bot with the following features: - πŸ₯£ Beautiful Soup- To scrape the data beautifully. - πŸ›Œ REST APIs - to fetch quotes and jokes for the fellows - 🐍 Python - The beautiful language to write our dynamic code. +- πŸŽ† Google API: The calendar API for getting the events +- πŸ“„ GitHub Pages: For hosting the FellowBot wesbite ## Bot commands ### Functionality 1 -> answering your MLH handbook related questions @@ -58,6 +61,9 @@ The project is a discord bot with the following features: ### Functionality 3 -> Emergency Hotline numbers Use ![your emergency] to trigger out helper bot or just enter **!all** to get every helpline number. +### Functionality 4 -> Get upcoming event(s) info +Use !event [count] to get a list of the ongoing and upcoming events of the pod. Enter the count of events to retrieve following the command. It's default value is 1. + ## Scalability 🌺 The project can be scaled to fulfill huge possibilities. The current scalable paths comprise of : - Extending the functionality to make the bot more dynamic i.e. text summarization for cosine similarity between asked questions. This will enable us to make our bot more useful. @@ -74,6 +80,11 @@ The project can be scaled to fulfill huge possibilities. The current scalable pa - copy the link in your own browser and authorize the bot. - Voila! Your bot is ready! +## Adding the bot to your server +- Enter your server token in the FellowBot website to add the bot your server +- Make a PR with your details in `Fellows.csv` to get access to confidential information restricted to MLH Fellows +- Yippee! You are done. + ## Contributing πŸ‘¬ Being open-source fellows, we used this opportunity to invite contributions from the whole MLH family!. The project is hence hosted as open source and you are welcome to make it more scalable and better ! From 8d5d9a05b2bc4386b9ef099c3d41eede5f4f6363 Mon Sep 17 00:00:00 2001 From: "George A. McCarthy" <65653499+georgeamccarthy@users.noreply.github.com> Date: Tue, 15 Jun 2021 14:33:33 +0100 Subject: [PATCH 11/20] Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index d3f41a6..d4455dd 100644 --- a/README.md +++ b/README.md @@ -93,3 +93,5 @@ We agree that the handbook should be of use to the MLH fellows hence the bot sho ## What we are proud of ? πŸ₯³ Since none of us had any idea about creating Discord bot, the hard work we have put in and the hours we spent on coding made us believe what we as a team can do. Even though we were running late by 2 days, we still decided to start a new project from scratch since it was more useful and ambitious. The experience was thrilling and we had/still having fun coding the project ! + +Created by Jyoti Bisht, Saurabh Agarwala and George A. McCarthy as part of the MLH summer 2021 orientation week hackathon. From acd41392452de6d71c6cefb0fbb254058e36ee14 Mon Sep 17 00:00:00 2001 From: Joe Date: Thu, 2 Sep 2021 19:48:02 +0530 Subject: [PATCH 12/20] added ruby version of discord bot --- README.md | 3 ++ config.txt | 0 fellowbot.rb | 134 +++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 137 insertions(+) create mode 100644 config.txt create mode 100644 fellowbot.rb diff --git a/README.md b/README.md index d4455dd..319fce8 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,9 @@ Talk πŸ’  Get help πŸ’  Scrape! +## Note : Ruby version of this bot resides in ./fellowbot.rb file +## Note : movierecsys feature of the discord bot can be found in this [repo](https://github.com/joeyouss/Movierecsys_Joebot) + ### **This is FellowBot - an MLH kickoff project, a bot and your friend!.** We understand how sometimes life in particular can be difficult and since we are now MLH Fellows, we thought of making something which can be used by every fellow in the server and which makes their life easy. diff --git a/config.txt b/config.txt new file mode 100644 index 0000000..e69de29 diff --git a/fellowbot.rb b/fellowbot.rb new file mode 100644 index 0000000..f2733cb --- /dev/null +++ b/fellowbot.rb @@ -0,0 +1,134 @@ +require 'discordrb' +config = File.foreach('config.txt').map { |line| line.split(' ').join(' ') } +token = config[0].to_s +bot = Discordrb::Commands::CommandBot.new token: "#{token}", client_id: "#{config[1].to_s}", prefix: "#{config[2].to_s}" + +helplines = ["Family Violence Prevention Center 1-800-313-1310", + "National Sexual Assault Hotline 1-800-656-HOPE (4673)", + "Drug Abuse National Helpline 1-800-662-4357", + "American Cancer Society 1-800-227-2345", + "Eating Disorders Awareness and Prevention 1-800-931-2237", + "GriefShare 1-800-395-5755", + "Suicide Hotline 1-800-SUICIDE (784-2433)"] + + # -------------------------MENTAL WELL BEING BOT +greetings = ["hi", "hello","how are you", "whats up","hey"] +sad_words = ["sad", "depressed", "unhappy", "angry", "miserable", "stressed", "hopeless", "unhappy","worthless"] +problems = ["time management", "busy", "impostor", "coding"] +suicide = ["kill myself", "kill yourself","suicidal","death"] + +# ------------replies +greet = [ + "Welcome !. What can I do for you?", + "Hi!!", + "I am so excited to have you here!", + "Hello there, I am an MLH bot here for your help", + "No I am sleeping right now. Just kidding !! how may I help you?" +] + +starter_encouragements = [ + "At times you may feel like this and I understand that, but it won't be for long I can assure you", + "Trying going for a walk and disconnecting with your surroundings and listen to music. The best way to cope up is to take a break", + "I hear you, MLH is there for you. Please talk to your pod leader and tell him in detail what problems are you facing in, he/she will be dhtere for you like we all are", + "You are doing great. If it counts, I am proud of you ! Don't feel like you cannot do better, you ofcourse can!" +] + +copeup=[ + "I can understand totally. But do you know how can you cope up?. Let me help you : 1. Divide your time into blocks", + "and make sure you are being generous to yourself.", + "2. Make sure you drink enough water and go out for a walk when your mind gets cluttered.", + "3. A little music does not hurt anyone.", + "4. We as coders feel as impostors all the time, don't worry just make sure you have faith on yourself", + "I can totally understand, have you ever tried the pomodore technique.? Read about it here - https://en.wikipedia.org/wiki/Pomodoro_Technique#:~:text=The%20Pomodoro%20Technique%20is%20a%20time%20management%20method,25%20minutes%20in%20length%2C%20separated%20by%20short%20breaks. " +] + +positivereply = [ + "We are extremely sorry to hear that you feel like this , but you are not alone in this. We as MLH put your well being as the top priority. Come talk to us what is bothering you. Help is available, speak with a counselor today by calling the National Suicide Prevention Lifeline at 800-273-8255", + "WE ARE THERE FOR YOU!!. When you think life isn't worth it, search for some new options. Help is available, speak with a counselor today by calling the National Suicide Prevention Lifeline at 800-273-8255" +] +bot.command :ping do |msg| + msg.respond "pong." +end + +bot.command :test do |event| + event.respond helplines[0] +end + +bot.message(start_with: '!game') do |event| + + magic = rand(1..10) + + event.respond "Can you guess my secret number? It's between 1 and 10!" + event.user.await!(timeout: 300) do |guess_event| + guess = guess_event.message.content.to_i + + if guess == magic + guess_event.respond 'you win!' + true + else + guess_event.respond(guess > magic ? 'too high' : 'too low') + false + end + end + event.respond "My number was: `#{magic}`." + end + + +CROSS_MARK = "\u274c" + + +bot.message(content: '!time') do |event| + message = event.respond "The current time is: #{Time.now.strftime('%F %T %Z')}" + + message.react CROSS_MARK + bot.add_await!(Discordrb::Events::ReactionAddEvent, message: message, emoji: CROSS_MARK, timeout: 30) do |_reaction_event| + message.delete + end + puts 'Await destroyed.' + end + +bot.message(contains: sad_words) do |event| + event.respond +end +bot.run + +# @bot.event +# async def on_message(message): +# flag = False +# gify = False +# await bot.process_commands(message) +# msg = message.content +# if message.author == bot.user: +# return +# if any(word in msg for word in greetings): +# gify = True +# response = random.choice(greet) +# await message.channel.send(response) + +# if any(word in msg for word in sad_words): +# flag = True +# response = random.choice(starter_encouragements) +# await message.channel.send(response) + +# if any(word in msg for word in problems): +# flag = True +# response = random.choice(copeup) +# await message.channel.send(response) + +# if any(word in msg for word in suicide): +# flag = True +# response = random.choice(positivereply) +# await message.channel.send(response) + +# if(flag): +# r1 = "And just to brighten your day, here is a joke for you" +# await message.channel.send(r1) +# r2 = joke() +# await message.channel.send(r2) + +# if 'quote' in msg.lower(): +# response = get_qoute() +# await message.channel.send(response) + + +# @bot.command(name='faq', help="\ From 27b56e8da8e533abe39b45d5c67d1f2d62591899 Mon Sep 17 00:00:00 2001 From: Joe Date: Fri, 3 Sep 2021 00:13:04 +0530 Subject: [PATCH 13/20] added REST API usage in ruby --- fellowbot.rb | 120 +++++++++++++++++++++++++++++++-------------------- 1 file changed, 74 insertions(+), 46 deletions(-) diff --git a/fellowbot.rb b/fellowbot.rb index f2733cb..8529019 100644 --- a/fellowbot.rb +++ b/fellowbot.rb @@ -46,14 +46,53 @@ "We are extremely sorry to hear that you feel like this , but you are not alone in this. We as MLH put your well being as the top priority. Come talk to us what is bothering you. Help is available, speak with a counselor today by calling the National Suicide Prevention Lifeline at 800-273-8255", "WE ARE THERE FOR YOU!!. When you think life isn't worth it, search for some new options. Help is available, speak with a counselor today by calling the National Suicide Prevention Lifeline at 800-273-8255" ] + + + +# ------> function zone +def jokes() + url = "https://v2.jokeapi.dev/joke/Programming,Miscellaneous,Christmas?blacklistFlags=nsfw,political,racist,sexist,explicit&type=twopart" + res = RestClient.get(url) + res = JSON.parse(res) + puts(res) + joke= "" + joke= res["setup"] + " - " + res["delivery"] + return joke +end + + +def quotes() + url = "https://zenquotes.io/api/random" + res = RestClient.get(url) + json_data = JSON.parse(res) + quote = "" + quote = json_data[0]['q'] + " -" + json_data[0]['a'] + return quote +end + + +# ------> function zone ends + +# -------> command zone bot.command :ping do |msg| msg.respond "pong." end bot.command :test do |event| - event.respond helplines[0] + event.respond helplines.sample end + +bot.command :jokes do |event| + event.respond jokes() +end + +bot.command :quote do |event| + event.respond quotes() +end + +# ----------> command zone ends +# ----- game section bot.message(start_with: '!game') do |event| magic = rand(1..10) @@ -73,7 +112,30 @@ event.respond "My number was: `#{magic}`." end - +# --------> trivial msg section +if bot.message(contains: sad_words) do |event| + event.respond positivereply.sample + event.respond "here is a joke to make you feel better" + event.respond jokes() + end +end + +if bot.message(contains: greetings) do |event| + event.respond greet.sample + end +end + +if bot.message(contains: problems) do |event| + event.respond copeup.sample + end +end + +if bot.message(contains: suicide ) do |event| + event.respond positivereply.sample + end +end + +# ------> time zone section CROSS_MARK = "\u274c" @@ -85,50 +147,16 @@ message.delete end puts 'Await destroyed.' - end +end + +# ------Γ· exit bot section +bot.command(:exit, help_available: false) do |event| + break unless event.user.id == 882697654348447774 + bot.send_message(event.channel.id, 'Bot is shutting down') + exit +end -bot.message(contains: sad_words) do |event| - event.respond -end bot.run -# @bot.event -# async def on_message(message): -# flag = False -# gify = False -# await bot.process_commands(message) -# msg = message.content -# if message.author == bot.user: -# return -# if any(word in msg for word in greetings): -# gify = True -# response = random.choice(greet) -# await message.channel.send(response) - -# if any(word in msg for word in sad_words): -# flag = True -# response = random.choice(starter_encouragements) -# await message.channel.send(response) - -# if any(word in msg for word in problems): -# flag = True -# response = random.choice(copeup) -# await message.channel.send(response) - -# if any(word in msg for word in suicide): -# flag = True -# response = random.choice(positivereply) -# await message.channel.send(response) - -# if(flag): -# r1 = "And just to brighten your day, here is a joke for you" -# await message.channel.send(r1) -# r2 = joke() -# await message.channel.send(r2) - -# if 'quote' in msg.lower(): -# response = get_qoute() -# await message.channel.send(response) - - -# @bot.command(name='faq', help="\ + + From 0b315690eb00c33874cbf7f97708040e5f265165 Mon Sep 17 00:00:00 2001 From: Joe Date: Fri, 3 Sep 2021 02:15:08 +0530 Subject: [PATCH 14/20] added scraping handbook feature --- fellowbot.rb | 110 +++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 97 insertions(+), 13 deletions(-) diff --git a/fellowbot.rb b/fellowbot.rb index 8529019..76bc230 100644 --- a/fellowbot.rb +++ b/fellowbot.rb @@ -1,8 +1,16 @@ require 'discordrb' +require 'json' + config = File.foreach('config.txt').map { |line| line.split(' ').join(' ') } token = config[0].to_s bot = Discordrb::Commands::CommandBot.new token: "#{token}", client_id: "#{config[1].to_s}", prefix: "#{config[2].to_s}" +# -----> CONSTANTS + +file = File.read('ok.json') +data_hash = JSON.parse(file) + + helplines = ["Family Violence Prevention Center 1-800-313-1310", "National Sexual Assault Hotline 1-800-656-HOPE (4673)", "Drug Abuse National Helpline 1-800-662-4357", @@ -11,7 +19,7 @@ "GriefShare 1-800-395-5755", "Suicide Hotline 1-800-SUICIDE (784-2433)"] - # -------------------------MENTAL WELL BEING BOT +# -------------------------MENTAL WELL BEING BOT greetings = ["hi", "hello","how are you", "whats up","hey"] sad_words = ["sad", "depressed", "unhappy", "angry", "miserable", "stressed", "hopeless", "unhappy","worthless"] problems = ["time management", "busy", "impostor", "coding"] @@ -46,8 +54,23 @@ "We are extremely sorry to hear that you feel like this , but you are not alone in this. We as MLH put your well being as the top priority. Come talk to us what is bothering you. Help is available, speak with a counselor today by calling the National Suicide Prevention Lifeline at 800-273-8255", "WE ARE THERE FOR YOU!!. When you think life isn't worth it, search for some new options. Help is available, speak with a counselor today by calling the National Suicide Prevention Lifeline at 800-273-8255" ] - - +MLH_keys_traversal =["MLHintro", "MLHevents", "pods", "discord", "zoom", "feedback", "remote", "hackathonrules","hackjudge", "hackdemo", "attendance", "expectations", "help"] + +MLH_keys = [ + "πŸ˜„ **MLHintro** - For in depth introduction to MLH fellowship.", + "🌲 **MLHevents**- What are MLH events? Know everything about them.", + "- πŸš‚ **pods** - What are pods? Know everything here", + "- πŸ“± **discord** -How to use discord and which channel serves what purpose", + "- πŸ“ž **zoom**- What is zoom used for?", + "- πŸ“’ **feedback** - What is feedback in MLH?", + "- ⏰ **remote** - How to work remotely and give your 100% in MLH.", + "- πŸ“ **hackathonrules** - Rules for hackathons", + "- πŸ₯‡ **hackjudge** - How do judges make a decision for hackathon winner? What is taken into consideration?", + "- πŸ’― **hackdemo** - How to prepare a good demo for hackathon?", + "- πŸ™‹ **attendance** - What is the importance of attendance in MLH and how is it monitored?", + "- πŸ’ **expectations** - What MLH expects from you as fellows", + "- ⛑️ **help** - Facing problems in MLH? Reach out to us" +] # ------> function zone def jokes() @@ -60,7 +83,6 @@ def jokes() return joke end - def quotes() url = "https://zenquotes.io/api/random" res = RestClient.get(url) @@ -74,6 +96,73 @@ def quotes() # ------> function zone ends # -------> command zone + +bot.command :MLHintro do |event| + for i in data_hash["intents"] do + if i["tag"] == "MLHintro" + for k in i["responses"] do + event.respond k + end + end + end +end + +bot.command :MLHevents do |event| + for i in data_hash["intents"] do + if i["tag"] == "MLHevents" + for k in i["responses"] do + event.respond k + end + end + end +end + +bot.command :pods do |event| + for i in data_hash["intents"] do + if i["tag"] == "pods" + for k in i["responses"] do + event.respond k + end + end + end +end + +bot.command :discord do |event| + for i in data_hash["intents"] do + if i["tag"] == "discord" + for k in i["responses"] do + event.respond k + end + end + end +end + +bot.command :attendance do |event| + for i in data_hash["intents"] do + if i["tag"] == "attendance" + for k in i["responses"] do + event.respond k + end + end + end +end + +bot.command :remote do |event| + for i in data_hash["intents"] do + if i["tag"] == "remote" + for k in i["responses"] do + event.respond k + end + end + end +end + +bot.command :mlh do |event| + for i in MLH_keys do + event.respond i + end +end + bot.command :ping do |msg| msg.respond "pong." end @@ -89,8 +178,7 @@ def quotes() bot.command :quote do |event| event.respond quotes() -end - +end # ----------> command zone ends # ----- game section bot.message(start_with: '!game') do |event| @@ -113,6 +201,8 @@ def quotes() end # --------> trivial msg section + + if bot.message(contains: sad_words) do |event| event.respond positivereply.sample event.respond "here is a joke to make you feel better" @@ -134,11 +224,8 @@ def quotes() event.respond positivereply.sample end end - # ------> time zone section CROSS_MARK = "\u274c" - - bot.message(content: '!time') do |event| message = event.respond "The current time is: #{Time.now.strftime('%F %T %Z')}" @@ -156,7 +243,4 @@ def quotes() exit end -bot.run - - - +bot.run \ No newline at end of file From cca81f9ad3a9051733076f827b0f13f8977f8c8a Mon Sep 17 00:00:00 2001 From: Joe Date: Fri, 3 Sep 2021 23:33:26 +0530 Subject: [PATCH 15/20] added sentimental analysis for bot and google translate --- FellowBot.py | 506 ++++++++++++++++++++++++++++++++++++++++++++++++++ sentiments.py | 26 +++ translate.py | 25 +++ 3 files changed, 557 insertions(+) create mode 100644 sentiments.py create mode 100644 translate.py diff --git a/FellowBot.py b/FellowBot.py index 1195b7b..164fb55 100644 --- a/FellowBot.py +++ b/FellowBot.py @@ -1,4 +1,12 @@ #Google Calendar API imports +#!/usr/bin/env python3 +from motivation import get_motivation, refresh_reddit_token +from connect_database import update_mood, get_moods +from mood import tone_result +from weekly_mood import weekly_moods +from google_translate import google_translate +from watson import reload_watson_api + from __future__ import print_function import datetime import os.path @@ -18,6 +26,501 @@ # enter token for the server # TOKEN = os.environ['DISCORD_TOKEN'] # to use in repl +import discord +from discord.ext import commands, tasks + +import datetime +import json +import random +import os + + +# --- + +TEST = True + +announcement_channels_list = [] + +try: + with open('config/config.json') as config_file: + conf = json.load(config_file) + if conf['token'] is None: + raise Exception + token = conf['token'] + if TEST: + token = conf['token_test'] + + +except Exception: + print("Failed to open config, check it exists and is valid.") + +bot = commands.Bot(command_prefix='>', description="CheckinWithMe") + +dmfailed = discord.Embed( + title="DM Failed", + description='', + timestamp=datetime.datetime.utcnow(), + color=discord.Color.from_rgb(240, 71, 71) +) + +day_of_week = datetime.datetime.today().weekday() # returns a number from 0 to 6 +daily_motivation = [ + "Hey, I know it's Monday. But it's also a new day and a new week. " + "And in that lies a new opportunity for something special to happen.", + + "Tuesday isn't so bad... It's a sign that I've somehow survived Monday.", + + "Wednesday is like small friday; half way to the weekend.", + + "Thankful Thursday, it's not happy people who are thankful. " + "It's thankful people who are happy. Always look on the bright side of life", + + "TGIF!", + + "Saturday - it's a good day to have a good day!", + + "Sunday: A day to refuel your soul and be grateful for your blessings. " + "Take a deep breath and realx. Enjoy your family, your friends and a cup of coffee." +] +days_of_the_week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] + + +# Static + +def update_announcement_list(): + global announcement_channels_list + announcement_channels_list = [] + for guild in bot.guilds: + for channel in guild.channels: + if str(channel.type) == 'text': + if str(channel.name) == "daily-check-in": + announcement_channels_list.append(channel) + + +def tone_response(tone, language="en"): + # Switch statements couldn't come fast enough + # TODO Switch statements on Python 3.10 release + if tone: + if tone == -1: + return -1 + elif tone['tone_id'] == 'anger': + return anger_response(language) + elif tone['tone_id'] == 'fear': + return fear_response(language) + elif tone['tone_id'] == 'sadness': + return sad_response(language) + elif tone['tone_id'] == 'joy': + return joy_response(language) + else: + return no_tone(language) + else: + return no_tone(language) + + +def joy_response(language): + embed = discord.Embed( + # Translate Title, if Language is English, Google Translate will not alter the string + + title=google_translate("It sounds like you're having an awesome day!", language)["translatedText"], + description=google_translate("""Happiness looks different for everyone, but it is often described as involving """ + + """positive emotions and life satisfaction. Perhaps you've had a rough few days and things have just started """ + + """to look up. Everyone experiences the ups and downs of life, but today is one of the good ones 😊.""", + language)["translatedText"], + timestamp=datetime.datetime.utcnow(), + color=discord.Color.from_rgb(252, 252, 153) + ) + embed.add_field(name=google_translate("Advice", language)["translatedText"], + value=google_translate("""Take the time to do something you enjoy, develop positive habits or work """ + + """towards one of your goals today to increase your happiness and """ + + """life satisfaction in the long run. """ + + """\nGive this article a read for tips to maintain happiness: """, + language)["translatedText"]) + embed.add_field(name='\u200b', value='\u200b') + embed.add_field(name='\u200b', value='\u200b') + + embed.add_field(name=google_translate("Resource", language)["translatedText"], + value=f"[{google_translate('10 Things Happy People Do to Stay Happy', language)['translatedText']}" + f"](https://tinybuddha.com/blog/10-things-happy-people-do-to-stay-happy/)") + embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/845318994666848261/845399136249053205/logo_guy.png") + return embed + + +def sad_response(language): + embed = discord.Embed( + title=google_translate("It looks like you might be feeling a little down.", language)["translatedText"], + description=google_translate("We all feel sad at times. Sadness is a normal human emotion that can make life " + "more interesting and teach us to appreciate happiness when it comes. That said, " + "sadness can be overwhelming at times and lead us into a downward spiral if " + "not dealt with. Here are some tips to work through sadness:", + language)["translatedText"], + timestamp=datetime.datetime.utcnow(), + color=discord.Color.from_rgb(168, 228, 239) + ) + + embed.add_field(name=google_translate("Get out in nature", language)["translatedText"], + value=google_translate("Spending time outdoors can improve your mood and " + "take your mind off your problems and widen your perspectives to beyond " + "the current situation.", language)["translatedText"]) + embed.add_field(name='\u200b', value='\u200b') + embed.add_field(name='\u200b', value='\u200b') + + embed.add_field(name=google_translate("Talk to someone.", language)["translatedText"], + value=google_translate("This could be a friend, therapist, or family member," + " someone you trust to listen to and comfort you if needed." + " Many online services such as " + "KidsHelpPhone also provide support for those in need.", + language)["translatedText"]) + embed.add_field(name='\u200b', value='\u200b') + embed.add_field(name='\u200b', value='\u200b') + + embed.add_field(name=google_translate("Take it one day at a time", language)["translatedText"], + value=google_translate("Do one thing to work towards improving your mental state today, " + "such as going for a walk or connecting with an old friend. " + "Do another tomorrow. Over time these little actions will build up.", + language)["translatedText"]) + embed.add_field(name='\u200b', value='\u200b') + embed.add_field(name='\u200b', value='\u200b') + + embed.add_field(name=google_translate("Give yourself time and permission to be sad", language)["translatedText"], + value=google_translate("Bottling up your feelings will do more harm than good over time. " + "Don't be afraid to seek help or express your feelings through " + "crying if you feel like it. ", language)["translatedText"]) + embed.add_field(name='\u200b', value='\u200b') + embed.add_field(name='\u200b', value='\u200b') + + embed.add_field(name=google_translate("Remember, it will get better", language)["translatedText"], + value=google_translate("You may not feel like it now, but what may seem so significant " + "today may not even matter in the future.", language)["translatedText"]) + embed.add_field(name='\u200b', value='\u200b') + embed.add_field(name='\u200b', value='\u200b') + + embed.add_field(name=google_translate("Resource", language)["translatedText"], + value=f"[{google_translate('10 Ways to Cheer Yourself Up When You’re in a Bad Mood', language)['translatedText']}" + f"](https://www.lifehack.org/articles/lifestyle/10-ways-cheer-yourself-when-youre-bad-mood.html)") + embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/845308432666853400/845752208297427034/logo_guy_but_sad.png") + return embed + + +def anger_response(language): + embed = discord.Embed( + title=google_translate("I think you might be angry.", language)["translatedText"], + description=google_translate("""Remember that it’s perfectly reasonable to get angry. """ + + """Something that can help is letting out your anger and venting; holding it in can make it worse. """ + + """Try out the resource below, or use `>resource` """ + + """for some more great resources to help improve your mental health.""", language)["translatedText"], + timestamp=datetime.datetime.utcnow(), + color=discord.Color.from_rgb(251, 105, 98) + ) + embed.add_field(name=google_translate("Resource", language)["translatedText"], + value=f"[{google_translate('How To Cool Off When Youre Angry', language)['translatedText']}" + f"](https://www.thehotline.org/resources/how-to-cool-off-when-youre-angry/)") + embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/845308432666853400/845752208297427034/logo_guy_but_sad.png") + return embed + + +def fear_response(language): + embed = discord.Embed( + title=google_translate("It looks like you’re experiencing fear/anxiety.", language)["translatedText"], + description=google_translate("""I totally get that life can be overwhelming and stressful. """ + + """You might be able to get over your fears by trying to take a step back and distracting yourself. """ + + """You can often get in your own head and make your fears worse. """ + + """Try the resource below, or use `>resource` for some more great resources to help improve your mental health.""", + language)["translatedText"], + timestamp=datetime.datetime.utcnow(), + color=discord.Color.from_rgb(168, 228, 239) + ) + embed.add_field(name=google_translate("Resource", language)["translatedText"], + value=f"[**{google_translate('NHS Inform', language)['translatedText']}** - " + f"{google_translate('Ten Ways to Fight Your Fears', language)['translatedText']}]" + f"(https://www.nhsinform.scot/healthy-living/mental-wellbeing/fears-and-phobias/ten-ways-to-fight-your-fears)") + embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/845308432666853400/845752208297427034/logo_guy_but_sad.png") + return embed + + +def no_tone(language): + embed = discord.Embed(title=google_translate("Oops!", language)['translatedText'], + description=google_translate("Sorry! I couldn't quite pinpoint how you are feeling. " + "Feel free to send me another message and " + "I'll try to figure out how you are feeling!", + language)["translatedText"], + timestamp=datetime.datetime.utcnow(), + color=discord.Color.from_rgb(61, 72, 73)) + + embed.add_field(name=">rate", value=google_translate("You can also let me know how you are feeling with `>rate`!", + language)['translatedText']) + embed.add_field(name='\u200b', value='\u200b') + embed.add_field(name=google_translate("Usage:", language)['translatedText'], + value="`>rate `") + embed.add_field(name='\u200b', value='\u200b') + embed.add_field(name='\u200b', value='\u200b') + embed.add_field(name=google_translate("Example", language)['translatedText'], + value=google_translate("If I'm feeling happy, I would `>rate Joy` 😊", language)['translatedText']) + embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/845318994666848261/845399136249053205/logo_guy.png") + return embed + + +def negative_ambiguous(language): + embed = discord.Embed( + title=google_translate("It looks like you might be feeling a little down.", language)['translatedText'], + description=google_translate("We all have our ups and downs! Remember, sometimes, it's okay to not feel okay. " + "Feel free to send me another message and " + "I'll try to figure out how you are feeling!", language)['translatedText'], + timestamp=datetime.datetime.utcnow(), color=discord.Color.from_rgb(153, 50, 204) + ) + + embed.add_field(name=">rate", value=google_translate("You can also let me know how you are feeling with `>rate`!", + language)['translatedText']) + embed.add_field(name='\u200b', value='\u200b') + embed.add_field(name=google_translate("Usage:", language)['translatedText'], + value="`>rate `") + embed.add_field(name='\u200b', value='\u200b') + embed.add_field(name='\u200b', value='\u200b') + embed.add_field(name=google_translate("Example", language)['translatedText'], + value=google_translate("If I'm feeling happy, I would `>rate Joy` 😊", language)['translatedText']) + embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/845308432666853400/845752208297427034/logo_guy_but_sad.png") + return embed + + +# Commands + + +@bot.command() +async def ping(ctx): + await ctx.send('pong') + + +@bot.command(pass_context=True) +async def checkin(ctx, *, message=None): + """ + Determines the user's mood by using IBM Watson's tone reader & Google Cloud's Natural Language Library + and uploads it to the database. + """ + if message: + translate = google_translate(message) + translation = translate["translatedText"] + language = translate["detectedSourceLanguage"] + tone = tone_result(translation) # tone detection from ML libraries + response = tone_response(tone, language) + + if tone: + if response == -1: + await ctx.send(embed=negative_ambiguous(language)) + elif response: + my_tone = tone['tone_id'] + update_mood(ctx.message.author.id, my_tone) + await ctx.send(embed=response) + else: + await ctx.send(embed=response) + else: + await ctx.send(embed=response) + else: + await ctx.send("Please follow `>checkin` with a description of how you're feeling!") + + +@bot.command(pass_context=True) +async def rate(ctx, *, message=None): + """ + When the tone reader fails to determine a mood, the user can + simply enter their mood and update the database with their mood + """ + if message: + rating = message.strip().lower() + if rating in ["anger", "fear", 'joy', 'sadness']: + tone = tone_result(rating) + my_tone = tone['tone_id'] + update_mood(ctx.message.author.id, my_tone) + response = tone_response(tone) + await ctx.send(embed=response) + else: + embed = discord.Embed(title="Oops!", description="Sorry! I couldn't quite pinpoint how you are feeling. " + "Feel free to send me another message and " + "I'll try to figure out how you are feeling!", + timestamp=datetime.datetime.utcnow(), color=discord.Color.from_rgb(61, 72, 73)) + embed.add_field(name="Usage:", value="`>rate `") + embed.add_field(name='\u200b', value='\u200b') + embed.add_field(name='\u200b', value='\u200b') + embed.add_field(name="Example", value="If I'm feeling happy, I would `>rate Joy` 😊") + embed.set_thumbnail( + url="https://cdn.discordapp.com/attachments/845318994666848261/845399136249053205/logo_guy.png" + ) + await ctx.send(embed=embed) + else: + await ctx.send("Please follow `>rate` with a description of how you're feeling!") + + +@bot.command(pass_context=True) +async def commands(ctx): + """ + Sends a list of the commands a user can use + """ + embed = discord.Embed(title="List of Commands", + description="To use these commands, type '`>`' with the corresponding command.", + timestamp=datetime.datetime.utcnow(), color=discord.Color.from_rgb(226, 83, 47)) + embed.add_field(name="checkin", value="""> Let me know how you're feeling with the 'checkin' command! For """+ + """instance, you could type `>checkin I'm feeling pretty happy today` or any other feelings you have.\n\n""" + + """> Your mood will then be categorized into one of four categories (anger, fear, joy, and sadness) """ + + """and will be compiled in a weekly summary for you to view at anytime.""" + ) + embed.add_field(name='\u200b', value='\u200b') + embed.add_field(name='\u200b', value='\u200b') + + embed.add_field(name="rate", value="""> You can also let me know how you are feeling with the 'rate' command! + > Please include one of the following: `| Anger | Fear | Joy | Sadness |` with the command.\n\n""" + + """> This provides a more direct and accurate method for our systems to track your mood.""" + ) + embed.add_field(name='\u200b', value='\u200b') + embed.add_field(name='\u200b', value='\u200b') + + embed.add_field(name="history", value="> Sends you a summary graphic of your mood over the last seven days.") + embed.add_field(name='\u200b', value='\u200b') + embed.add_field(name='\u200b', value='\u200b') + + embed.add_field(name="motivation", value="> Sends motivational messages to cheer you on to bigger and better.") + embed.add_field(name='\u200b', value='\u200b') + embed.add_field(name='\u200b', value='\u200b') + + embed.add_field(name="resource", value="> Generates a random resource to help you develop your mental health!") + + embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/845318994666848261/845399136249053205/logo_guy.png") + await ctx.send(embed=embed) + + +@bot.command() +async def motivation(ctx): + """ + Calls get_motivation() and which gets a reddit post from the top of r/GetMotivated + """ + motivation_url = get_motivation() + await ctx.send(motivation_url) + + +@bot.command() +async def resource(ctx): + """ + Sends a random resource from a list of mental health resources + """ + resources = [ + "https://www.mindful.org/meditation/mindfulness-getting-started/", + "https://www.mindful.org/how-to-meditate/", + "https://www.youtube.com/watch?v=inpok4MKVLM", + "https://gratefulness.org/", + "https://www.helpguide.org/articles/healthy-living/the-mental-health-benefits-of-exercise.htm", + "https://www.youtube.com/c/HealthyGamerGG/videos", + "https://psychcentral.com/", + "https://headtohealth.gov.au/", + "https://www.calmsage.com/", + "https://www.loveisrespect.org/resources/self-care-when-youre-angry/", + "https://www.youtube.com/playlist?list=PLQiGxGHwiuD1kdxsWKFuhE0rITIXe-7yC", + "https://reallifecounseling.us/overcome-fear-and-anxiety/" + ] + resource = random.choice(resources) + embed = discord.Embed(title="Random Resource", description=resource, timestamp=datetime.datetime.utcnow(), + color=discord.Color.from_rgb(226, 83, 47)) + await ctx.send(embed=embed) + + +@bot.command() +async def history(ctx): + """ + Uploads a graphic sunmmarizing your mood over the past seven days. + """ + user_id = ctx.message.author.id + weekly_moods(get_moods(user_id), user_id) + await ctx.send(file=discord.File(f'process/{user_id}.png')) + os.remove(f'process/{user_id}.png') + + +# Events + +@bot.event +async def on_guild_join(guild): + """ + Activates as the bot joins a discord server. + It sets its server permissions, creates a channel for daily checkins, sends an introductory + message, and sends the first daily checkin reminder. + """ + overwrites = { + guild.default_role: discord.PermissionOverwrite(read_messages=True), + guild.default_role: discord.PermissionOverwrite(send_messages=False), + guild.me: discord.PermissionOverwrite(read_messages=True), + guild.me: discord.PermissionOverwrite(send_messages=True), + } + await guild.create_text_channel('daily-check-in', overwrites=overwrites) + channel_id = discord.utils.get(guild.channels, name='daily-check-in').id + channel = bot.get_channel(channel_id) + update_announcement_list() + embed = discord.Embed(title="Hello World! πŸ‘‹", + description="""My name is Pip and I'm here to help you track your moods on the daily.""", + timestamp=datetime.datetime.utcnow(), color=discord.Color.from_rgb(255, 255, 77)) + embed.add_field(name="How I work", + value="> All you have to do is tell me how you're doing each day by *sending me a message*, " + "and a graphic from the last seven days will be compiled for you to view at anytime." + " Understanding and monitoring your moods is crucial to " + "managing them and feeling better faster. If you are " + "more aware of your moods, you may be able to better manage your lifestyle choices, " + "make informed health decisions, prevent or avoid triggers of negative moods, " + "and work towards a better quality of life. Best of luck on your mental health journey!" + "\n\nTo see a list of commands, type `>commands`!") + embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/845318994666848261/845399136249053205/logo_guy.png") + await channel.send(embed=embed) + + embed = discord.Embed(title=f"⭐ Happy {days_of_the_week[day_of_week]}! ⭐", + description="> Yesterday is history. " + "Tomorrow is a mystery, but today is a gift! " + "That is why it is called the present.", + timestamp=datetime.datetime.utcnow(), color=discord.Color.from_rgb(221, 160, 51)) + embed.add_field(name="Check in With Me!", value=f"{bot_tag.mention}") + embed.add_field(name='\u200b', value='\u200b') + embed.add_field(name='\u200b', value='\u200b') + embed.add_field(name="Daily Motivation", value=daily_motivation[day_of_week]) + embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/845318994666848261/845399136249053205/logo_guy.png") + await channel.send(embed=embed) + + +@bot.event +async def on_ready(): + if not os.path.exists('process'): + os.mkdir('process') + await bot.change_presence(activity=discord.Game("Let's check in! | prefix: >"), status="online") + global bot_tag + bot_tag = bot.user + update_announcement_list() + refresh_reddit_token() + reload_watson_api() + print('Bot Initialized') + + +# Tasks + +@tasks.loop(hours=1) +async def reload_tokens(): + """ + refreshes Reddit & Watson access token every hour + """ + refresh_reddit_token() + reload_watson_api() + + +@tasks.loop(hours=24) +async def checkin_announcement(): + """ + Sends a reminder every 24 hours to users to remind them to checkin and track their mood + """ + day_of_week = datetime.datetime.today().weekday() + for channel in announcement_channels_list: + embed = discord.Embed(title=f"⭐ Happy {days_of_the_week[day_of_week]}! ⭐", + description="> Yesterday is history. " + "Tomorrow is a mystery, but today is a gift! " + "That is why it is called the present.", + timestamp=datetime.datetime.utcnow(), color=discord.Color.from_rgb(221, 160, 51)) + embed.add_field(name="Check in With Me!", value=f"{bot_tag.mention}") + embed.add_field(name='\u200b', value='\u200b') + embed.add_field(name='\u200b', value='\u200b') + embed.add_field(name="Daily Motivation", value=daily_motivation[day_of_week]) + embed.set_thumbnail( + url="https://cdn.discordapp.com/attachments/845318994666848261/845399136249053205/logo_guy.png") + await channel.send(embed=embed) + from dotenv import load_dotenv load_dotenv() TOKEN = os.getenv('DISCORD_TOKEN') # for dev purpose @@ -259,5 +762,8 @@ async def on_message(message): # REPEATEDLY PING SERVER TO KEEP ALIVE #keepalive() +checkin_announcement.start() +reload_tokens.start() + # ---------------------INITIALIZING THE BOT bot.run(TOKEN) diff --git a/sentiments.py b/sentiments.py new file mode 100644 index 0000000..8eaa535 --- /dev/null +++ b/sentiments.py @@ -0,0 +1,26 @@ +# Imports the Google Cloud client library +from google.cloud import language_v1 +import os +import json + + +with open('config/config.json') as json_file: + config = json.load(json_file) + +os.environ["GOOGLE_APPLICATION_CREDENTIALS"]=config["G_CLOUD_SERVICE_KEYFILE"] + +client = language_v1.LanguageServiceClient() + + +def google_sentiment_analysis(text: str): + try: + document = language_v1.Document(content=text, type_=language_v1.Document.Type.PLAIN_TEXT) + sentiment = client.analyze_sentiment(request={'document': document}).document_sentiment + sentiment_score = { + "score": sentiment.score, + "magnitude": sentiment.magnitude + } + except Exception: + return None + output = sentiment_score if sentiment_score else None + return output diff --git a/translate.py b/translate.py new file mode 100644 index 0000000..3503b05 --- /dev/null +++ b/translate.py @@ -0,0 +1,25 @@ +from google.cloud import translate_v2 as translate +import json +import os +import six +import html + +with open('config/config.json') as json_file: + config = json.load(json_file) + +os.environ["GOOGLE_APPLICATION_CREDENTIALS"]=config["G_CLOUD_SERVICE_KEYFILE"] + + +def google_translate(text, language="en"): + """ + Translates text into the target language + Target must be an ISO 639-1 language code. + See https://g.co/cloud/translate/v2/translate-reference#supported_languages + """ + translate_client = translate.Client() + + if isinstance(text, six.binary_type): + text = text.decode("utf-8") + result = translate_client.translate(text, target_language=language) + result['translatedText'] = html.unescape(result['translatedText']) # + return result From 04ab04de0d7aa2a7d1ff7b1597a87935d343c673 Mon Sep 17 00:00:00 2001 From: Joe Date: Fri, 3 Sep 2021 23:35:03 +0530 Subject: [PATCH 16/20] added IBM watson API --- moods.py | 66 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ watson.py | 33 ++++++++++++++++++++++++++++ 2 files changed, 99 insertions(+) create mode 100644 moods.py create mode 100644 watson.py diff --git a/moods.py b/moods.py new file mode 100644 index 0000000..c40cb02 --- /dev/null +++ b/moods.py @@ -0,0 +1,66 @@ +from PIL import Image, ImageDraw, ImageFont +import datetime + + +def draw_block(start, difference, moods): + daily_moods = [] # list of moods (no repeats) + mood_count = {} # count of each mood + highest = 0 # highest count of a mood + + for mood in moods: # just sorts through the day's moods for above vars + if mood not in daily_moods: + daily_moods.append(mood) + mood_count[mood] = moods.count(mood) + if moods.count(mood) > highest: + highest = moods.count(mood) + + daily_moods = sorted(daily_moods) # alpha sort so the bars have some order + + increment = difference / len(daily_moods) # separation of bars + coord_list = [[start]] # beginning left coord of box + + for i in range(len(daily_moods)): # makes list of x coords between all increments and y displacement + lower_x = start + (increment * (i + 1)) + y_coord = (1 - (mood_count[daily_moods[i]] / highest)) * 93 + coord_list.append([lower_x, y_coord]) + + return coord_list, daily_moods + + +def weekly_moods(moods: list, uuid: int): + # defines colours of bars (missing 'confident': 'orange', 'tentative': 'green', 'analytical': 'pink') + colours = { + 'anger': (251, 105, 98), + 'fear': (168, 228, 239), + 'joy': (252, 252, 153), + 'sadness': (121, 222, 121) + } + lower = 260 # lower is the bottom coord of bar, upper is top but it changes + upper = 167 + difference = 93 # difference between the 2 sides of the boxes + blocks = [857, 722, 586, 450, 313, 176, 44] # left coord of each box + + back = Image.open("resource/grey_back.png") # grey background with the boxes + back_draw = ImageDraw.Draw(back) + + for i in range(len(blocks)): + if len(moods[i]) != 0: + coords, daily_moods = draw_block(blocks[i], difference, moods[i]) # for each box, the function is called + + for j in range(len(daily_moods)): + back_draw.rectangle((coords[j][0] + 1, upper + coords[j + 1][1], coords[j + 1][0], lower), + fill=colours[daily_moods[j]]) # draws each mood for each box + + # date text + today = datetime.datetime.now().date() + initial_coord = 860 + difference = 134 + scale = 1.2 + font = ImageFont.truetype("resource/Roboto-Regular.ttf", 17) + + for i in range(7): + back_draw.text((initial_coord - (difference * i) - (i * scale), 270), (today - datetime.timedelta(i + 1) + ).strftime('%m/%d/%Y'), + fill=(119, 131, 211), font=font) + + back.save(f"process/{uuid}.png") diff --git a/watson.py b/watson.py new file mode 100644 index 0000000..da0508a --- /dev/null +++ b/watson.py @@ -0,0 +1,33 @@ +from ibm_cloud_sdk_core.authenticators import IAMAuthenticator +from ibm_watson import ToneAnalyzerV3 +import json + + +with open('config/watson.json') as json_file: + watson_setup = json.load(json_file) + +def reload_watson_api(): + global ta + watson_authenticator = IAMAuthenticator(watson_setup['API_key']) # authentication + ta = ToneAnalyzerV3(version='2017-09-21', authenticator=watson_authenticator) # sets up analyzer instance + ta.set_service_url(watson_setup['url']) + + +language_tones = ['analytical', 'confident', 'tentative'] + + +def watson_tone_analysis(message: str) -> dict: + results = ta.tone(message).get_result() + most_confident_score = {'score': 0} + + for tone in results['document_tone']['tones']: + if tone['tone_id'] not in language_tones: + # Ignore language indicators + if tone['score'] > most_confident_score['score']: + most_confident_score = tone + if most_confident_score == {'score': 0}: + return None + else: + return most_confident_score + +reload_watson_api() \ No newline at end of file From f553462199657c4abbdeac84a60b10de1eef229e Mon Sep 17 00:00:00 2001 From: Joe Date: Fri, 3 Sep 2021 23:41:19 +0530 Subject: [PATCH 17/20] updated readme --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 319fce8..ba0053c 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ Talk πŸ’  Get help πŸ’  Scrape! ## Note : Ruby version of this bot resides in ./fellowbot.rb file ## Note : movierecsys feature of the discord bot can be found in this [repo](https://github.com/joeyouss/Movierecsys_Joebot) - +## Note : sentimental analysis to make bot more dynamic is now supported. ### **This is FellowBot - an MLH kickoff project, a bot and your friend!.** We understand how sometimes life in particular can be difficult and since we are now MLH Fellows, we thought of making something which can be used by every fellow in the server and which makes their life easy. From 1ca820c5a6f1736823892305d5a1fb0a66375ac0 Mon Sep 17 00:00:00 2001 From: Joe Date: Fri, 3 Sep 2021 23:49:22 +0530 Subject: [PATCH 18/20] hmm idk --- FellowBot.py | 23 +++++------------------ 1 file changed, 5 insertions(+), 18 deletions(-) diff --git a/FellowBot.py b/FellowBot.py index 164fb55..341675c 100644 --- a/FellowBot.py +++ b/FellowBot.py @@ -98,8 +98,6 @@ def update_announcement_list(): def tone_response(tone, language="en"): - # Switch statements couldn't come fast enough - # TODO Switch statements on Python 3.10 release if tone: if tone == -1: return -1 @@ -119,8 +117,7 @@ def tone_response(tone, language="en"): def joy_response(language): embed = discord.Embed( - # Translate Title, if Language is English, Google Translate will not alter the string - + title=google_translate("It sounds like you're having an awesome day!", language)["translatedText"], description=google_translate("""Happiness looks different for everyone, but it is often described as involving """ + """positive emotions and life satisfaction. Perhaps you've had a rough few days and things have just started """ + @@ -291,10 +288,7 @@ async def ping(ctx): @bot.command(pass_context=True) async def checkin(ctx, *, message=None): - """ - Determines the user's mood by using IBM Watson's tone reader & Google Cloud's Natural Language Library - and uploads it to the database. - """ + if message: translate = google_translate(message) translation = translate["translatedText"] @@ -319,10 +313,7 @@ async def checkin(ctx, *, message=None): @bot.command(pass_context=True) async def rate(ctx, *, message=None): - """ - When the tone reader fails to determine a mood, the user can - simply enter their mood and update the database with their mood - """ + if message: rating = message.strip().lower() if rating in ["anger", "fear", 'joy', 'sadness']: @@ -494,18 +485,14 @@ async def on_ready(): @tasks.loop(hours=1) async def reload_tokens(): - """ - refreshes Reddit & Watson access token every hour - """ + refresh_reddit_token() reload_watson_api() @tasks.loop(hours=24) async def checkin_announcement(): - """ - Sends a reminder every 24 hours to users to remind them to checkin and track their mood - """ + day_of_week = datetime.datetime.today().weekday() for channel in announcement_channels_list: embed = discord.Embed(title=f"⭐ Happy {days_of_the_week[day_of_week]}! ⭐", From 06f719904b524ca845b11d3da34de9cfe22651aa Mon Sep 17 00:00:00 2001 From: "Jyoti Bisht (Joe)" Date: Wed, 15 Sep 2021 18:50:47 +0530 Subject: [PATCH 19/20] reverted back to event changes to make code cleaner --- FellowBot.py | 488 +-------------------------------------------------- config.txt | 3 + fellowbot.rb | 7 +- 3 files changed, 15 insertions(+), 483 deletions(-) diff --git a/FellowBot.py b/FellowBot.py index 341675c..6466fa7 100644 --- a/FellowBot.py +++ b/FellowBot.py @@ -34,493 +34,19 @@ import random import os - -# --- - TEST = True +# ---------------------BOT COMMAND +bot = commands.Bot(command_prefix='!') +# ---------------------WEB SCRAPING +scraping = open("faq.json", encoding="UTF-8") +scraped = json.load(scraping) announcement_channels_list = [] -try: - with open('config/config.json') as config_file: - conf = json.load(config_file) - if conf['token'] is None: - raise Exception - token = conf['token'] - if TEST: - token = conf['token_test'] - - -except Exception: - print("Failed to open config, check it exists and is valid.") - -bot = commands.Bot(command_prefix='>', description="CheckinWithMe") - -dmfailed = discord.Embed( - title="DM Failed", - description='', - timestamp=datetime.datetime.utcnow(), - color=discord.Color.from_rgb(240, 71, 71) -) - -day_of_week = datetime.datetime.today().weekday() # returns a number from 0 to 6 -daily_motivation = [ - "Hey, I know it's Monday. But it's also a new day and a new week. " - "And in that lies a new opportunity for something special to happen.", - - "Tuesday isn't so bad... It's a sign that I've somehow survived Monday.", - - "Wednesday is like small friday; half way to the weekend.", - - "Thankful Thursday, it's not happy people who are thankful. " - "It's thankful people who are happy. Always look on the bright side of life", - - "TGIF!", - - "Saturday - it's a good day to have a good day!", - - "Sunday: A day to refuel your soul and be grateful for your blessings. " - "Take a deep breath and realx. Enjoy your family, your friends and a cup of coffee." -] -days_of_the_week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] - - -# Static - -def update_announcement_list(): - global announcement_channels_list - announcement_channels_list = [] - for guild in bot.guilds: - for channel in guild.channels: - if str(channel.type) == 'text': - if str(channel.name) == "daily-check-in": - announcement_channels_list.append(channel) - - -def tone_response(tone, language="en"): - if tone: - if tone == -1: - return -1 - elif tone['tone_id'] == 'anger': - return anger_response(language) - elif tone['tone_id'] == 'fear': - return fear_response(language) - elif tone['tone_id'] == 'sadness': - return sad_response(language) - elif tone['tone_id'] == 'joy': - return joy_response(language) - else: - return no_tone(language) - else: - return no_tone(language) - - -def joy_response(language): - embed = discord.Embed( - - title=google_translate("It sounds like you're having an awesome day!", language)["translatedText"], - description=google_translate("""Happiness looks different for everyone, but it is often described as involving """ + - """positive emotions and life satisfaction. Perhaps you've had a rough few days and things have just started """ + - """to look up. Everyone experiences the ups and downs of life, but today is one of the good ones 😊.""", - language)["translatedText"], - timestamp=datetime.datetime.utcnow(), - color=discord.Color.from_rgb(252, 252, 153) - ) - embed.add_field(name=google_translate("Advice", language)["translatedText"], - value=google_translate("""Take the time to do something you enjoy, develop positive habits or work """ + - """towards one of your goals today to increase your happiness and """ + - """life satisfaction in the long run. """ + - """\nGive this article a read for tips to maintain happiness: """, - language)["translatedText"]) - embed.add_field(name='\u200b', value='\u200b') - embed.add_field(name='\u200b', value='\u200b') - - embed.add_field(name=google_translate("Resource", language)["translatedText"], - value=f"[{google_translate('10 Things Happy People Do to Stay Happy', language)['translatedText']}" - f"](https://tinybuddha.com/blog/10-things-happy-people-do-to-stay-happy/)") - embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/845318994666848261/845399136249053205/logo_guy.png") - return embed - - -def sad_response(language): - embed = discord.Embed( - title=google_translate("It looks like you might be feeling a little down.", language)["translatedText"], - description=google_translate("We all feel sad at times. Sadness is a normal human emotion that can make life " - "more interesting and teach us to appreciate happiness when it comes. That said, " - "sadness can be overwhelming at times and lead us into a downward spiral if " - "not dealt with. Here are some tips to work through sadness:", - language)["translatedText"], - timestamp=datetime.datetime.utcnow(), - color=discord.Color.from_rgb(168, 228, 239) - ) - - embed.add_field(name=google_translate("Get out in nature", language)["translatedText"], - value=google_translate("Spending time outdoors can improve your mood and " - "take your mind off your problems and widen your perspectives to beyond " - "the current situation.", language)["translatedText"]) - embed.add_field(name='\u200b', value='\u200b') - embed.add_field(name='\u200b', value='\u200b') - - embed.add_field(name=google_translate("Talk to someone.", language)["translatedText"], - value=google_translate("This could be a friend, therapist, or family member," - " someone you trust to listen to and comfort you if needed." - " Many online services such as " - "KidsHelpPhone also provide support for those in need.", - language)["translatedText"]) - embed.add_field(name='\u200b', value='\u200b') - embed.add_field(name='\u200b', value='\u200b') - - embed.add_field(name=google_translate("Take it one day at a time", language)["translatedText"], - value=google_translate("Do one thing to work towards improving your mental state today, " - "such as going for a walk or connecting with an old friend. " - "Do another tomorrow. Over time these little actions will build up.", - language)["translatedText"]) - embed.add_field(name='\u200b', value='\u200b') - embed.add_field(name='\u200b', value='\u200b') - - embed.add_field(name=google_translate("Give yourself time and permission to be sad", language)["translatedText"], - value=google_translate("Bottling up your feelings will do more harm than good over time. " - "Don't be afraid to seek help or express your feelings through " - "crying if you feel like it. ", language)["translatedText"]) - embed.add_field(name='\u200b', value='\u200b') - embed.add_field(name='\u200b', value='\u200b') - - embed.add_field(name=google_translate("Remember, it will get better", language)["translatedText"], - value=google_translate("You may not feel like it now, but what may seem so significant " - "today may not even matter in the future.", language)["translatedText"]) - embed.add_field(name='\u200b', value='\u200b') - embed.add_field(name='\u200b', value='\u200b') - - embed.add_field(name=google_translate("Resource", language)["translatedText"], - value=f"[{google_translate('10 Ways to Cheer Yourself Up When You’re in a Bad Mood', language)['translatedText']}" - f"](https://www.lifehack.org/articles/lifestyle/10-ways-cheer-yourself-when-youre-bad-mood.html)") - embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/845308432666853400/845752208297427034/logo_guy_but_sad.png") - return embed - - -def anger_response(language): - embed = discord.Embed( - title=google_translate("I think you might be angry.", language)["translatedText"], - description=google_translate("""Remember that it’s perfectly reasonable to get angry. """ + - """Something that can help is letting out your anger and venting; holding it in can make it worse. """ + - """Try out the resource below, or use `>resource` """ + - """for some more great resources to help improve your mental health.""", language)["translatedText"], - timestamp=datetime.datetime.utcnow(), - color=discord.Color.from_rgb(251, 105, 98) - ) - embed.add_field(name=google_translate("Resource", language)["translatedText"], - value=f"[{google_translate('How To Cool Off When Youre Angry', language)['translatedText']}" - f"](https://www.thehotline.org/resources/how-to-cool-off-when-youre-angry/)") - embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/845308432666853400/845752208297427034/logo_guy_but_sad.png") - return embed - - -def fear_response(language): - embed = discord.Embed( - title=google_translate("It looks like you’re experiencing fear/anxiety.", language)["translatedText"], - description=google_translate("""I totally get that life can be overwhelming and stressful. """ + - """You might be able to get over your fears by trying to take a step back and distracting yourself. """ + - """You can often get in your own head and make your fears worse. """ + - """Try the resource below, or use `>resource` for some more great resources to help improve your mental health.""", - language)["translatedText"], - timestamp=datetime.datetime.utcnow(), - color=discord.Color.from_rgb(168, 228, 239) - ) - embed.add_field(name=google_translate("Resource", language)["translatedText"], - value=f"[**{google_translate('NHS Inform', language)['translatedText']}** - " - f"{google_translate('Ten Ways to Fight Your Fears', language)['translatedText']}]" - f"(https://www.nhsinform.scot/healthy-living/mental-wellbeing/fears-and-phobias/ten-ways-to-fight-your-fears)") - embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/845308432666853400/845752208297427034/logo_guy_but_sad.png") - return embed - - -def no_tone(language): - embed = discord.Embed(title=google_translate("Oops!", language)['translatedText'], - description=google_translate("Sorry! I couldn't quite pinpoint how you are feeling. " - "Feel free to send me another message and " - "I'll try to figure out how you are feeling!", - language)["translatedText"], - timestamp=datetime.datetime.utcnow(), - color=discord.Color.from_rgb(61, 72, 73)) - - embed.add_field(name=">rate", value=google_translate("You can also let me know how you are feeling with `>rate`!", - language)['translatedText']) - embed.add_field(name='\u200b', value='\u200b') - embed.add_field(name=google_translate("Usage:", language)['translatedText'], - value="`>rate `") - embed.add_field(name='\u200b', value='\u200b') - embed.add_field(name='\u200b', value='\u200b') - embed.add_field(name=google_translate("Example", language)['translatedText'], - value=google_translate("If I'm feeling happy, I would `>rate Joy` 😊", language)['translatedText']) - embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/845318994666848261/845399136249053205/logo_guy.png") - return embed - - -def negative_ambiguous(language): - embed = discord.Embed( - title=google_translate("It looks like you might be feeling a little down.", language)['translatedText'], - description=google_translate("We all have our ups and downs! Remember, sometimes, it's okay to not feel okay. " - "Feel free to send me another message and " - "I'll try to figure out how you are feeling!", language)['translatedText'], - timestamp=datetime.datetime.utcnow(), color=discord.Color.from_rgb(153, 50, 204) - ) - - embed.add_field(name=">rate", value=google_translate("You can also let me know how you are feeling with `>rate`!", - language)['translatedText']) - embed.add_field(name='\u200b', value='\u200b') - embed.add_field(name=google_translate("Usage:", language)['translatedText'], - value="`>rate `") - embed.add_field(name='\u200b', value='\u200b') - embed.add_field(name='\u200b', value='\u200b') - embed.add_field(name=google_translate("Example", language)['translatedText'], - value=google_translate("If I'm feeling happy, I would `>rate Joy` 😊", language)['translatedText']) - embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/845308432666853400/845752208297427034/logo_guy_but_sad.png") - return embed - - -# Commands - - -@bot.command() -async def ping(ctx): - await ctx.send('pong') - - -@bot.command(pass_context=True) -async def checkin(ctx, *, message=None): - - if message: - translate = google_translate(message) - translation = translate["translatedText"] - language = translate["detectedSourceLanguage"] - tone = tone_result(translation) # tone detection from ML libraries - response = tone_response(tone, language) - - if tone: - if response == -1: - await ctx.send(embed=negative_ambiguous(language)) - elif response: - my_tone = tone['tone_id'] - update_mood(ctx.message.author.id, my_tone) - await ctx.send(embed=response) - else: - await ctx.send(embed=response) - else: - await ctx.send(embed=response) - else: - await ctx.send("Please follow `>checkin` with a description of how you're feeling!") - - -@bot.command(pass_context=True) -async def rate(ctx, *, message=None): - - if message: - rating = message.strip().lower() - if rating in ["anger", "fear", 'joy', 'sadness']: - tone = tone_result(rating) - my_tone = tone['tone_id'] - update_mood(ctx.message.author.id, my_tone) - response = tone_response(tone) - await ctx.send(embed=response) - else: - embed = discord.Embed(title="Oops!", description="Sorry! I couldn't quite pinpoint how you are feeling. " - "Feel free to send me another message and " - "I'll try to figure out how you are feeling!", - timestamp=datetime.datetime.utcnow(), color=discord.Color.from_rgb(61, 72, 73)) - embed.add_field(name="Usage:", value="`>rate `") - embed.add_field(name='\u200b', value='\u200b') - embed.add_field(name='\u200b', value='\u200b') - embed.add_field(name="Example", value="If I'm feeling happy, I would `>rate Joy` 😊") - embed.set_thumbnail( - url="https://cdn.discordapp.com/attachments/845318994666848261/845399136249053205/logo_guy.png" - ) - await ctx.send(embed=embed) - else: - await ctx.send("Please follow `>rate` with a description of how you're feeling!") - - -@bot.command(pass_context=True) -async def commands(ctx): - """ - Sends a list of the commands a user can use - """ - embed = discord.Embed(title="List of Commands", - description="To use these commands, type '`>`' with the corresponding command.", - timestamp=datetime.datetime.utcnow(), color=discord.Color.from_rgb(226, 83, 47)) - embed.add_field(name="checkin", value="""> Let me know how you're feeling with the 'checkin' command! For """+ - """instance, you could type `>checkin I'm feeling pretty happy today` or any other feelings you have.\n\n""" + - """> Your mood will then be categorized into one of four categories (anger, fear, joy, and sadness) """ + - """and will be compiled in a weekly summary for you to view at anytime.""" - ) - embed.add_field(name='\u200b', value='\u200b') - embed.add_field(name='\u200b', value='\u200b') - - embed.add_field(name="rate", value="""> You can also let me know how you are feeling with the 'rate' command! - > Please include one of the following: `| Anger | Fear | Joy | Sadness |` with the command.\n\n""" + - """> This provides a more direct and accurate method for our systems to track your mood.""" - ) - embed.add_field(name='\u200b', value='\u200b') - embed.add_field(name='\u200b', value='\u200b') - - embed.add_field(name="history", value="> Sends you a summary graphic of your mood over the last seven days.") - embed.add_field(name='\u200b', value='\u200b') - embed.add_field(name='\u200b', value='\u200b') - - embed.add_field(name="motivation", value="> Sends motivational messages to cheer you on to bigger and better.") - embed.add_field(name='\u200b', value='\u200b') - embed.add_field(name='\u200b', value='\u200b') - - embed.add_field(name="resource", value="> Generates a random resource to help you develop your mental health!") - - embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/845318994666848261/845399136249053205/logo_guy.png") - await ctx.send(embed=embed) - - -@bot.command() -async def motivation(ctx): - """ - Calls get_motivation() and which gets a reddit post from the top of r/GetMotivated - """ - motivation_url = get_motivation() - await ctx.send(motivation_url) - - -@bot.command() -async def resource(ctx): - """ - Sends a random resource from a list of mental health resources - """ - resources = [ - "https://www.mindful.org/meditation/mindfulness-getting-started/", - "https://www.mindful.org/how-to-meditate/", - "https://www.youtube.com/watch?v=inpok4MKVLM", - "https://gratefulness.org/", - "https://www.helpguide.org/articles/healthy-living/the-mental-health-benefits-of-exercise.htm", - "https://www.youtube.com/c/HealthyGamerGG/videos", - "https://psychcentral.com/", - "https://headtohealth.gov.au/", - "https://www.calmsage.com/", - "https://www.loveisrespect.org/resources/self-care-when-youre-angry/", - "https://www.youtube.com/playlist?list=PLQiGxGHwiuD1kdxsWKFuhE0rITIXe-7yC", - "https://reallifecounseling.us/overcome-fear-and-anxiety/" - ] - resource = random.choice(resources) - embed = discord.Embed(title="Random Resource", description=resource, timestamp=datetime.datetime.utcnow(), - color=discord.Color.from_rgb(226, 83, 47)) - await ctx.send(embed=embed) - - -@bot.command() -async def history(ctx): - """ - Uploads a graphic sunmmarizing your mood over the past seven days. - """ - user_id = ctx.message.author.id - weekly_moods(get_moods(user_id), user_id) - await ctx.send(file=discord.File(f'process/{user_id}.png')) - os.remove(f'process/{user_id}.png') - - -# Events - -@bot.event -async def on_guild_join(guild): - """ - Activates as the bot joins a discord server. - It sets its server permissions, creates a channel for daily checkins, sends an introductory - message, and sends the first daily checkin reminder. - """ - overwrites = { - guild.default_role: discord.PermissionOverwrite(read_messages=True), - guild.default_role: discord.PermissionOverwrite(send_messages=False), - guild.me: discord.PermissionOverwrite(read_messages=True), - guild.me: discord.PermissionOverwrite(send_messages=True), - } - await guild.create_text_channel('daily-check-in', overwrites=overwrites) - channel_id = discord.utils.get(guild.channels, name='daily-check-in').id - channel = bot.get_channel(channel_id) - update_announcement_list() - embed = discord.Embed(title="Hello World! πŸ‘‹", - description="""My name is Pip and I'm here to help you track your moods on the daily.""", - timestamp=datetime.datetime.utcnow(), color=discord.Color.from_rgb(255, 255, 77)) - embed.add_field(name="How I work", - value="> All you have to do is tell me how you're doing each day by *sending me a message*, " - "and a graphic from the last seven days will be compiled for you to view at anytime." - " Understanding and monitoring your moods is crucial to " - "managing them and feeling better faster. If you are " - "more aware of your moods, you may be able to better manage your lifestyle choices, " - "make informed health decisions, prevent or avoid triggers of negative moods, " - "and work towards a better quality of life. Best of luck on your mental health journey!" - "\n\nTo see a list of commands, type `>commands`!") - embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/845318994666848261/845399136249053205/logo_guy.png") - await channel.send(embed=embed) - - embed = discord.Embed(title=f"⭐ Happy {days_of_the_week[day_of_week]}! ⭐", - description="> Yesterday is history. " - "Tomorrow is a mystery, but today is a gift! " - "That is why it is called the present.", - timestamp=datetime.datetime.utcnow(), color=discord.Color.from_rgb(221, 160, 51)) - embed.add_field(name="Check in With Me!", value=f"{bot_tag.mention}") - embed.add_field(name='\u200b', value='\u200b') - embed.add_field(name='\u200b', value='\u200b') - embed.add_field(name="Daily Motivation", value=daily_motivation[day_of_week]) - embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/845318994666848261/845399136249053205/logo_guy.png") - await channel.send(embed=embed) - - -@bot.event -async def on_ready(): - if not os.path.exists('process'): - os.mkdir('process') - await bot.change_presence(activity=discord.Game("Let's check in! | prefix: >"), status="online") - global bot_tag - bot_tag = bot.user - update_announcement_list() - refresh_reddit_token() - reload_watson_api() - print('Bot Initialized') - - -# Tasks - -@tasks.loop(hours=1) -async def reload_tokens(): - - refresh_reddit_token() - reload_watson_api() - - -@tasks.loop(hours=24) -async def checkin_announcement(): - - day_of_week = datetime.datetime.today().weekday() - for channel in announcement_channels_list: - embed = discord.Embed(title=f"⭐ Happy {days_of_the_week[day_of_week]}! ⭐", - description="> Yesterday is history. " - "Tomorrow is a mystery, but today is a gift! " - "That is why it is called the present.", - timestamp=datetime.datetime.utcnow(), color=discord.Color.from_rgb(221, 160, 51)) - embed.add_field(name="Check in With Me!", value=f"{bot_tag.mention}") - embed.add_field(name='\u200b', value='\u200b') - embed.add_field(name='\u200b', value='\u200b') - embed.add_field(name="Daily Motivation", value=daily_motivation[day_of_week]) - embed.set_thumbnail( - url="https://cdn.discordapp.com/attachments/845318994666848261/845399136249053205/logo_guy.png") - await channel.send(embed=embed) - -from dotenv import load_dotenv -load_dotenv() -TOKEN = os.getenv('DISCORD_TOKEN') # for dev purpose - # If modifying these scopes, delete the file token.json. SCOPES = ['https://www.googleapis.com/auth/calendar.readonly'] -# ---------------------BOT COMMAND -bot = commands.Bot(command_prefix='!') -# ---------------------WEB SCRAPING -scraping = open("faq.json", encoding="UTF-8") -scraped = json.load(scraping) # ----------------FOR HELPLINE helplines = ["Family Violence Prevention Center 1-800-313-1310", "National Sexual Assault Hotline 1-800-656-HOPE (4673)", @@ -689,9 +215,7 @@ async def eatingdisorder(ctx): ] # -------------------------TRIGGERING BOT EVENT -@bot.event -async def on_ready(): - print('Bot is ready.') + #-------------------------RANDOM QUOTE SUGGESTION def get_qoute(): response = requests.get("https://zenquotes.io/api/random") diff --git a/config.txt b/config.txt index e69de29..e58adb6 100644 --- a/config.txt +++ b/config.txt @@ -0,0 +1,3 @@ +ODgyNjk3NjU0MzQ4NDQ3Nzc0.YS_KQA.D9dTYYAKFm2bLTkpZ8hI8bN5NMs +882697654348447774 +! \ No newline at end of file diff --git a/fellowbot.rb b/fellowbot.rb index 76bc230..b384674 100644 --- a/fellowbot.rb +++ b/fellowbot.rb @@ -202,7 +202,12 @@ def quotes() # --------> trivial msg section - +if bot.message(contains: "intro") do |event| + for i in MLH_keys do + event.respond i + end +end +end if bot.message(contains: sad_words) do |event| event.respond positivereply.sample event.respond "here is a joke to make you feel better" From cd53037ebc67dcaf3785c5836d65041231fbbda1 Mon Sep 17 00:00:00 2001 From: "Jyoti Bisht (Joe)" Date: Wed, 15 Sep 2021 18:51:46 +0530 Subject: [PATCH 20/20] watson API compromised --- watson.py | 33 --------------------------------- 1 file changed, 33 deletions(-) delete mode 100644 watson.py diff --git a/watson.py b/watson.py deleted file mode 100644 index da0508a..0000000 --- a/watson.py +++ /dev/null @@ -1,33 +0,0 @@ -from ibm_cloud_sdk_core.authenticators import IAMAuthenticator -from ibm_watson import ToneAnalyzerV3 -import json - - -with open('config/watson.json') as json_file: - watson_setup = json.load(json_file) - -def reload_watson_api(): - global ta - watson_authenticator = IAMAuthenticator(watson_setup['API_key']) # authentication - ta = ToneAnalyzerV3(version='2017-09-21', authenticator=watson_authenticator) # sets up analyzer instance - ta.set_service_url(watson_setup['url']) - - -language_tones = ['analytical', 'confident', 'tentative'] - - -def watson_tone_analysis(message: str) -> dict: - results = ta.tone(message).get_result() - most_confident_score = {'score': 0} - - for tone in results['document_tone']['tones']: - if tone['tone_id'] not in language_tones: - # Ignore language indicators - if tone['score'] > most_confident_score['score']: - most_confident_score = tone - if most_confident_score == {'score': 0}: - return None - else: - return most_confident_score - -reload_watson_api() \ No newline at end of file