Giter VIP home page Giter VIP logo

twitchbot's Introduction

Simple Bot Build status

Custom chat bot for Twitch TV

This is an open-source console application with a .NET Core Web API that will benefit anyone who wants to have a foundation of making their own Twitch bot. This is primarly written in C#/SQL Server using an Azure SQL database from Microsoft. Currently, this bot is not end-user friendly because I'm concentrating on the logic of the bot first.

For developers, please read further down for details on manually setting a dev configuration so the information is always saved.

Check out the wiki for the full list of commands by clicking here!

The bot itself is an account on Twitch that I have made in order to have a custom bot name.

For a development environment (testing), create an AppConfigSecrets.config in the same folder as App.config. If you have any issues setting up this bot, please look further below for possible solutions.

Twitch Chat OAuth Password Generator

The chat bot needs access to the IRC chat in order to communicate with the broadcaster and their viewers.

While you're signed into the chat bot account on Twitch, connect to the Twitch Chat OAuth Password Generator site and grab the oauth:XXXXXXXXXXXXXX string for the twitchOAuth config variable.

Twitch OAuth Implicit Access Token

In order for the chat bot to run correctly, we need a few permissions:

  • channel:manage:broadcast
  • channel:read:subscriptions
  • moderation:read
  • user:read:email

For more information on the permissions above, please refer to the scope documentation here.

NOTE: You'll need to add your own Client-ID since this will be based on a proxy/alternate Twitch account for the chat bot. Also, we will be utilizing http://localhost for development purposes.

This is the "complete" request URL you'll paste into your browser and allow the chat bot access to your channel.

https://id.twitch.tv/oauth2/authorize?client_id=<client id goes here>&redirect_uri=http://localhost&response_type=token&scope=user:read:email+channel:read:subscriptions+channel:manage:broadcast+moderation:read

This is the "complete" response URL you'll see in your browser once you authenticate implicitly. Copy the access token from the response URL and paste it into the twitchAccessToken config variable.

http://localhost/#access_token=<copy access token from here>&scope=<scopes assigned from above>&token_type=bearer

For further documentation on "OAuth Implicit Code Flow", please refer to this link here.

AppConfigSecrets.config

<TwitchBotConfiguration 
    botName="" 
    broadcaster="" 
    currencyType=""
    discordServerName=""
    discordToken=""
    enableDisplaySong="false"
    enableTweets="false" 
    libVLCAudioOutputDevice=""
    regularFollowerHours="30"
    showUserConsoleLog="false"
    spotifyClientId=""
    spotifyRedirectUri=""
    streamLatency="10" 
    twitchBotApiLink=""
    twitchOAuth="" 
    twitchClientId=""
    twitchAccessToken="" 
    twitterConsumerKey="" 
    twitterConsumerSecret=""
    twitterAccessToken="" 
    twitterAccessSecret="" 
    youTubeClientId="" 
    youTubeClientSecret=""
    youTubeBroadcasterPlaylistId=""
    youTubeBroadcasterPlaylistName="" />

Set file to copy-if-newer so it's included in the compilation. For production, this file is not needed and the bot will ask for configuration on first run

Spotify Example Setup

Go to the Spotify Developer Dashboard and create a new app with these settings below:

  • Website:
    • http://localhost:5000
  • Redirect URL:
    • http://localhost:5000/callback

Of course if you're using your own web server, replace localhost with your domain. Here we're using HTTP for local reasons. Always use HTTPS outside of a local environment.

Possible Setup Issues:

  • IIS HTTP Error 404.11 - Not Found The request filtering module is configured to deny a request that contains a double escape sequence

Host Self-Contained ASP.NET Core Web API on Windows with IIS

Scaffold Commands

In case if you need to scaffold anything, here are some commands that may be useful

Models and DbContext

This is a single-line command using the "Package Manager Console" in Visual Studio that allows you to generate ALL of the models and the DbContext class.

Scaffold-DbContext 'Data Source=;Initial Catalog=;User ID=;Password=;' Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -ContextDir Context

If you only need the model and context of a SINGLE table, here's the single-line command for that.

Scaffold-DbContext 'Data Source=;Initial Catalog=;User ID=;Password=;' Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -ContextDir Context -T <TABLE_NAME_HERE>

twitchbot's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

twitchbot's Issues

Countdown

Implement a countdown system a moderator and above would use to display when something is going to happen. At the moment, only hold one countdown at a time until command is well tested.

Make a countdown:
!makecountdown "Happy New Year's" "1-1-2016 12:00:00 AM"

Display the countdown:
!displaycountdown
Countdown to Happy New Year's: 28 days, 7 hours, 33 minutes, and 42 seconds

Use similar logic from FollowSince with SubscribeSince

Add manual check if chatter listener doesn't have the user requesting this info.
Reference to CmdFollowSince()

TwitchChatter chatter = _twitchChatterListInstance.TwitchFollowers.FirstOrDefault(c => c.Username.Equals(username));

if (chatter == null)
{
    // get chatter info manually
    RootUserJSON rootUserJSON = await _twitchInfo.GetUsersByLoginName(username);

    using (HttpResponseMessage message = await _twitchInfo.CheckFollowerStatus(rootUserJSON.Users.First().Id))
    {
        string body = await message.Content.ReadAsStringAsync();
        FollowerJSON response = JsonConvert.DeserializeObject<FollowerJSON>(body);

        if (!string.IsNullOrEmpty(response.CreatedAt))
            chatter = new TwitchChatter { Username = username, CreatedAt = Convert.ToDateTime(response.CreatedAt) };
    }
}

// mainly used if chatter was originally null
if (chatter != null)
{
    DateTime startedFollowing = Convert.ToDateTime(chatter.CreatedAt);
    _irc.SendPublicChatMessage($"@{username} has been following since {startedFollowing.ToLongDateString()}");
}
else
{
    _irc.SendPublicChatMessage($"{username} is not following {_botConfig.Broadcaster.ToLower()}");
}

Personal Follow via Twitter

Let interested users know when the broadcaster is streaming a certain game that they prefer.

Channel owner makes a list of games they play and users can select which ones to be notified.

!top3[currency name]

Display the people under the current broadcaster who have the most amount of streamer currency

Auto Publish Tweets on Channel Info Change

Each time either !updatetitle or !updategame is used, make an option to tweet the changes made to the channel.

Make a boolean so it can be shared to both update commands inside the main function.

bool autoTweetChanges = true;

Get Current Song

In chat, get current song info like !currentsong

StatusResponse status = spotify.GetStatus();
if (status == null) return;

if (message.Contains("!currentsong")) 
    spotifyCtrl.ShowUpdatedTrack(status.Track, false);

!usage [cmd]

Help explain a command in-chat

Example Input: !usage sr
Example Output: The song request command is "!sr [artist] - [title]". It allows users to request songs to the broadcaster so they are aware what the viewers want to listen to.

MultiTwitch Link Generator

This should be a command that allows the broadcaster to generate a link to allow people to watch multiple streamers at the same time. This link uses a separate service like multitwitch.tv to provide the feed on a separate tab.

The purpose of this command will allow multiple streamers to "co-stream"
Example: http://multitwitch.tv/broadcaster/username2/username3/username4

Here are the commands for this feature:

!addmultitwitch [username2] [username3] [username4] (broadcaster only)

  • This commmand will require one parameter (with 3 optional parameters)
  • This should append users to the link if not all of the parameters were filled
  • 4 user limit for now...

!resetmultitwitch (broadcaster only)

  • Resets the link to only have the broadcaster attached to the link

!multitwitch (general chat)

  • Display multitwitch link to the chat if there are other users appended to the link

Return NotFound() With Content Message

Example: return NotFound("Warning: Chat bot cannot find [insert subject here]");
But be sure to include any Console.WriteLine(""); to immediately tell the user it has been loaded

Handle !currentsong using IF and ELSE

Rewrite command with this code:

StatusResponse status = spotify.GetStatus();
if (status != null) 
{
    irc.sendPublicChatMessage("Current Song: " + status.Track.TrackResource.Name
        + " || Artist: " + status.Track.ArtistResource.Name
        + " || Album: " + status.Track.AlbumResource.Name);
}
else
    irc.sendPublicChatMessage("The broadcaster is not playing a song at the moment");

This will handle the situation where Spotify is not playing anything

Blackjack

Make a Blackjack mini game with user's current funds

Custom Commands

Will create a separate branch and update this task list accordingly

  • Create database tables
CREATE SCHEMA Cmd;
GO

-- Pre-defined commands made by developer(s)
CREATE TABLE Cmd.PermissionLevel
(
    Id INT IDENTITY(1, 1) NOT NULL
  , PermissionName VARCHAR(20) NOT NULL
  , CONSTRAINT PK_Cmd_PermissionLevel
        PRIMARY KEY (Id)
);
CREATE TABLE Cmd.Method
(
    Id INT IDENTITY(1, 1) NOT NULL
  , MethodName VARCHAR(10) NOT NULL
  , CONSTRAINT PK_Cmd_Method
        PRIMARY KEY (Id)
);
CREATE TABLE Cmd.PredefinedCommand
(
    Id INT IDENTITY(1, 1) NOT NULL
  , Command VARCHAR(30) NOT NULL
  , MethodId INT NOT NULL
        FOREIGN KEY REFERENCES Cmd.Method (Id)
  , CONSTRAINT PK_Cmd_PredefinedCommand
        PRIMARY KEY CLUSTERED (Id)
);
CREATE TABLE Cmd.UserSetPredefinedCommand
(
    Id INT IDENTITY(1, 1) NOT NULL
  , MethodId INT NOT NULL
        FOREIGN KEY REFERENCES Cmd.Method (Id)
  , BroadcasterId INT NOT NULL
        FOREIGN KEY REFERENCES dbo.Broadcaster (Id)
  , PermissionId INT NOT NULL
        FOREIGN KEY REFERENCES Cmd.PermissionLevel (Id)
  , CONSTRAINT PK_Cmd_UserSetPredefinedCommand
        PRIMARY KEY (Id)
);

-- Custom commands
CREATE TABLE Cmd.CustomCommand
(
    Id INT IDENTITY(1, 1) NOT NULL
  , Command NVARCHAR(30) NOT NULL
  , Message NVARCHAR(500) NOT NULL
  , BroadcasterId INT NOT NULL
        FOREIGN KEY REFERENCES dbo.Broadcaster (Id)
  , PermissionId INT NOT NULL
        FOREIGN KEY REFERENCES Cmd.PermissionLevel (Id)
  , CONSTRAINT PK_Cmd_CustomCommand
        PRIMARY KEY (Id)
);
  • Create Models and DTOs
public enum PermissionLevel
{
    Viewer,
    VIP,
    Subscriber,
    Moderator,
    Broadcaster
}

public sealed class ChatCommand
{
    private readonly string _name;
    public readonly CommandName Value;

    public ChatCommand(string name, CommandName value)
    {
        _name = name;
        Value = value
    }

    public override string ToString()
    {
        return _name;
    }

    public enum CommandName
    {
        Quote = 1,
        FollowSince = 2,
        FollowAge = 3,
        Rank = 4,
        // add more
    }

    public static readonly ChatCommand Quote = new ChatCommand("!quote", Value.Quote);
    public static readonly ChatCommand FollowSince = new ChatCommand("!followsince", Value.FollowSince );
    public static readonly ChatCommand FollowAge = new ChatCommand("!followage", Value.FollowAge );
    public static readonly ChatCommand Rank = new ChatCommand("!rank", Value.Rank );
    // add more
}

Look into this StackOverflow answer as a reference for the sealed class ChatCommand

  • Re-write giant if block in TwitchBotApplication.cs to use custom commands with user-set permissions

...will write more later

!top3rank

Display the 3 highest ranking followers underneath a streamer

Remove UNIQUE attribute on Username column for Broadcasters table

Need to remove uniqueness because of this scenario:

Let's say we have two broadcasters A & B. Broadcaster A decided to change their name to Broadcaster C, but doesn't log back into the bot. After X amount of time passes, Broadcaster B changes their name to Broadcaster A. Now the new broadcaster A can't be added to this table because the old broadcaster A never logged back into the bot to notify the database of the name change.

Delete expired reminders

This will allow users to set an end date and time for reminders if a re-occurring event only lasts for X amount of time

Mods Giving Currency To Each Other

Don't allow moderators (bot or channel) to give each other currency via !deposit and !bonusall

Use _modInstance.Moderators list to check alongside _twitchChatterListInstance.ChattersByType

Grab Specific Quote Via Index

Get list of quotes in order of index from database and refer to the order given in memory. Use something like: !quote 1 to grab the first quote even thought the database index could be at 1002.

When grabbing the range of indexes, display that for the user so they know what is valid to grab.
Also, when displaying the quote, show the index assigned to it and get the user who quoted it.

!gamble all

Let user gamble away all of their currency

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.