8.6.3. Demo: Sentiment Analysis on Discord#

Choose Social Media Platform: Reddit | Discord | Bluesky | No Coding

Now let’s try using sentiment analysis (and loop variables) on Discord:

We’ll start by doing our normal steps to load the discord library (or fake discord)

Load “discord” and nest_asyncio libraries#

# Load some code called "discord" that will help us work with Discord
import discord

# Load another library that helps the bot work in Jupyter Noteboook
import nest_asyncio
nest_asyncio.apply()

(optional) make a fake Discord connection with the fake_discord library#

For testing purposes, we’ve added this line of code, which loads a fake version of Discord, so it wont actually connect to Discord. If you want to try to actually connect to Discord, don’t run this line of code.

%run ../../fake_apis/fake_discord.ipynb
Fake discord is replacing the discord.py library. Fake discord doesn't need real passwords, and prevents you from accessing real discord

set up your Discord connection#

To use this on your real Discord account, copy your discord token into the code below, replacing our fake passwords.

# Set up your Discord connection
# TODO: put the discord token for your bot below
discord_token = "m#5@_fake_discord_token_$%Ds"

# set up Discord client with permissions to read message_contents
intents = discord.Intents.default()
intents.message_content = True 

find a list of discord posts#

We can now make a bot that loads a list of discord posts.

Note: If you run this on real discord, we can’t gurantee anything about how offensive what you might find is.

# set up discord connection
client = discord.Client(intents=intents)

# TODO: put the discord channel id number below for the channel you want to use
channel_id = 123456789

# Provide instructions for what your discord bot should do once it has logged in
@client.event
async def on_ready():
    global recent_posts # Save the recent_posts variable outside our running bot
    
    # Load the discord channel you want to post to
    channel = client.get_channel(channel_id)

    # Get the latest post in the channel history
    post_history = channel.history(limit=10)
    
    #special code to turn the post_history from discord into a python list
    recent_posts = [post async for post in post_history]

    # Tell your bot to stop running
    await client.close()
    
# Now that we've defined how the bot shoould work, start running your bot
client.run(discord_token)
Fake discord is pretending to set up a client connection
Fake discord bot is fake logging in and starting to run
Fake discord bot is shutting down

Sentiment Analysis#

load sentiment analysis library and make analyzer#

import nltk
nltk.download(["vader_lexicon"])
from nltk.sentiment import SentimentIntensityAnalyzer
sia = SentimentIntensityAnalyzer()
[nltk_data] Downloading package vader_lexicon to
[nltk_data]     C:\Users\kmthayer\AppData\Roaming\nltk_data...
[nltk_data]   Package vader_lexicon is already up-to-date!

loop through submissions, finding average sentiment#

We can now combine our previous examples of looping through reddit submissions with what we just learned of sentiment analysis and looping variables to find the average sentiment of a set of submission titles.

num_posts = 0
total_sentiment = 0

for post in recent_posts:
    
    #calculate sentiment
    post_sentiment = sia.polarity_scores(post.content)["compound"]
    num_posts += 1
    total_sentiment += post_sentiment

    print("Sentiment: " + str(post_sentiment))
    print("   post content: " + post.content)
    print()


average_sentiment = total_sentiment / num_posts
print("Average sentiment was " + str(average_sentiment))
Sentiment: 0.784
   post content: Breaking news: A lovely cat took a nice long nap today!

Sentiment: 0.0
   post content: Breaking news: Someone said a really mean thing on the internet today!

Sentiment: 0.7088
   post content: Breaking news: Some grandparents made some yummy cookies for all the kids to share!

Sentiment: -0.6114
   post content: Breaking news: All the horrors of the universe revealed at last!

Average sentiment was 0.22034999999999996

We can now see the average sentiment of a set of discord posts!

If you use your reddit bot keys, you can change the channel_id to be whatever one you want and see whether people are posting positively or negatively in it.

note: You can change limit=10 to go up higher to get more submissions at a time to find the average of