Merge pull request #6 from pizzaandcoffee/upgrades

Upgrading to DotNetCore 2, upgrading discord sdk and a small change to dependency injection
This commit is contained in:
Daan Boerlage 2017-09-14 22:21:37 +02:00 committed by GitHub
commit ee94c7dabc
24 changed files with 489 additions and 666 deletions

View file

@ -1,33 +1,43 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp1.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Cleverbot" Version="0.9.0" />
<PackageReference Include="Discord.Net">
<Version>1.0.0-rc</Version>
</PackageReference>
<PackageReference Include="Google.Apis.YouTube.v3">
<Version>1.25.0.760</Version>
</PackageReference>
<PackageReference Include="HtmlAgilityPack.NetCore">
<Version>1.5.0.1</Version>
</PackageReference>
<PackageReference Include="RestSharp.NetCore">
<Version>105.2.4-rc4-24214-01</Version>
</PackageReference>
<PackageReference Include="StackExchange.Redis">
<Version>1.2.1</Version>
</PackageReference>
<PackageReference Include="System.Net.Http">
<Version>4.3.1</Version>
</PackageReference>
<PackageReference Include="System.Runtime.Serialization.Json">
<Version>4.3.0</Version>
</PackageReference>
<PackageReference Include="System.Runtime.Serialization.Primitives">
<Version>4.3.0</Version>
</PackageReference>
</ItemGroup>
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.0</TargetFramework>
<ApplicationIcon>derp.ico</ApplicationIcon>
<Version>1.1.0</Version>
<Company>Pizza and Coffee Studios</Company>
<Authors>Pizza and Coffee Studios</Authors>
<Description>A Discord bot</Description>
<RepositoryUrl>https://github.com/pizzaandcoffee/Geekbot.net</RepositoryUrl>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Discord.Net">
<Version>1.0.2</Version>
</PackageReference>
<PackageReference Include="Google.Apis.YouTube.v3">
<Version>1.29.1.976</Version>
</PackageReference>
<PackageReference Include="HtmlAgilityPack.NetCore">
<Version>1.5.0.1</Version>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="2.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="2.0.0" />
<PackageReference Include="Microsoft.Extensions.Options" Version="2.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="10.0.3" />
<PackageReference Include="RestSharp.NetCore">
<Version>105.2.3</Version>
</PackageReference>
<PackageReference Include="StackExchange.Redis">
<Version>1.2.6</Version>
</PackageReference>
<PackageReference Include="System.Net.Http">
<Version>4.3.2</Version>
</PackageReference>
<PackageReference Include="System.Runtime.Serialization.Formatters" Version="4.3.0" />
<PackageReference Include="System.Runtime.Serialization.Json">
<Version>4.3.0</Version>
</PackageReference>
<PackageReference Include="System.Runtime.Serialization.Primitives">
<Version>4.3.0</Version>
</PackageReference>
</ItemGroup>
</Project>

View file

@ -1,20 +0,0 @@
using System.Collections.Generic;
namespace Geekbot.net.Lib.Dtos
{
class FourChanDto
{
public class BoardList
{
public List<Board> Boards { get; set; }
}
public class Board
{
public string board { get; set; }
public string title { get; set; }
public string ws_board { get; set; }
public string meta_description { get; set; }
}
}
}

View file

@ -1,19 +0,0 @@
using RestSharp;
namespace Geekbot.net.Lib.IClients
{
public interface ICatClient
{
IRestClient Client { get; set; }
}
public class CatClient : ICatClient
{
public CatClient()
{
Client = new RestClient("http://random.cat");
}
public IRestClient Client { get; set; }
}
}

View file

@ -1,19 +0,0 @@
using RestSharp;
namespace Geekbot.net.Lib.IClients
{
public interface IDogClient
{
IRestClient Client { get; set; }
}
public class DogClient : IDogClient
{
public DogClient()
{
Client = new RestClient("http://random.dog");
}
public IRestClient Client { get; set; }
}
}

View file

@ -1,38 +0,0 @@
using RestSharp;
using System;
using System.Collections.Generic;
using static Geekbot.net.Lib.Dtos.FourChanDto;
namespace Geekbot.net.Lib.IClients
{
class FourChanBoardClient
{
private BoardList boards;
private static FourChanBoardClient instace;
private FourChanBoardClient()
{
Console.WriteLine("Fetching Boards");
var boardClient = new RestClient("https://a.4cdn.org");
var boardRequest = new RestRequest("boards.json", Method.GET);
var boardResult = boardClient.Execute<BoardList>(boardRequest);
this.boards = boardResult.Data;
}
public static FourChanBoardClient Boards()
{
if (instace == null)
{
instace = new FourChanBoardClient();
}
return instace;
}
public List<Board> getBoards()
{
return this.boards.Boards;
}
}
}

View file

@ -1,29 +0,0 @@
using System;
namespace Geekbot.net.Lib.IClients
{
public interface IRandomClient
{
Random Client { get; set; }
}
public sealed class RandomClient : IRandomClient
{
public RandomClient()
{
try
{
Client = new Random();
}
catch (Exception)
{
Console.WriteLine("Start Redis pls...");
Environment.Exit(1);
}
}
public Random Client { get; set; }
}
}

View file

@ -1,30 +0,0 @@
using System;
using StackExchange.Redis;
namespace Geekbot.net.Lib.IClients
{
public interface IRedisClient
{
IDatabase Client { get; set; }
}
public sealed class RedisClient : IRedisClient
{
public RedisClient()
{
try
{
var redis = ConnectionMultiplexer.Connect("127.0.0.1:6379");
Client = redis.GetDatabase(6);
}
catch (Exception)
{
Console.WriteLine("Start Redis pls...");
Environment.Exit(1);
}
}
public IDatabase Client { get; set; }
}
}

View file

@ -1,35 +1,34 @@
using System;
using System.Threading.Tasks;
using Discord.WebSocket;
using Geekbot.net.Lib.IClients;
using StackExchange.Redis;
namespace Geekbot.net.Lib
{
public class StatsRecorder
{
private readonly SocketMessage message;
private readonly IDatabase redis;
public StatsRecorder(SocketMessage message, IRedisClient redisClient)
{
this.message = message;
redis = redisClient.Client;
}
public async Task UpdateUserRecordAsync()
{
var guildId = ((SocketGuildChannel) message.Channel).Guild.Id;
var key = guildId + "-" + message.Author.Id + "-messages";
await redis.StringIncrementAsync(key);
}
public async Task UpdateGuildRecordAsync()
{
var guildId = ((SocketGuildChannel) message.Channel).Guild.Id;
var key = guildId + "-messages";
await redis.StringIncrementAsync(key);
}
}
using System;
using System.Threading.Tasks;
using Discord.WebSocket;
using StackExchange.Redis;
namespace Geekbot.net.Lib
{
public class StatsRecorder
{
private readonly SocketMessage message;
private readonly IDatabase redis;
public StatsRecorder(SocketMessage message, IDatabase redis)
{
this.message = message;
this.redis = redis;
}
public async Task UpdateUserRecordAsync()
{
var guildId = ((SocketGuildChannel) message.Channel).Guild.Id;
var key = guildId + "-" + message.Author.Id + "-messages";
await redis.StringIncrementAsync(key);
}
public async Task UpdateGuildRecordAsync()
{
var guildId = ((SocketGuildChannel) message.Channel).Guild.Id;
var key = guildId + "-messages";
await redis.StringIncrementAsync(key);
}
}
}

View file

@ -1,41 +1,41 @@
using System.Threading.Tasks;
using Discord.Commands;
using Geekbot.net.Lib.IClients;
namespace Geekbot.net.Modules
{
[Group("admin")]
public class AdminCmd : ModuleBase
{
private readonly IRedisClient redis;
public AdminCmd(IRedisClient redisClient)
{
redis = redisClient;
}
[RequireUserPermission(Discord.GuildPermission.Administrator)]
[Command("welcome", RunMode = RunMode.Async), Summary("Set a Welcome Message (use '$user' to mention the new joined user).")]
public async Task SetWelcomeMessage([Remainder, Summary("The message")] string welcomeMessage)
{
var key = Context.Guild.Id + "-welcomeMsg";
redis.Client.StringSet(key, welcomeMessage);
var formatedMessage = welcomeMessage.Replace("$user", Context.User.Mention);
await ReplyAsync("Welcome message has been changed\r\nHere is an example of how it would look:\r\n" +
formatedMessage);
}
[Command("youtubekey", RunMode = RunMode.Async), Summary("Set the youtube api key")]
public async Task SetYoutubeKey([Summary("API Key")] string key)
{
var botOwner = redis.Client.StringGet("botOwner");
if (!Context.User.Id.ToString().Equals(botOwner.ToString()))
{
await ReplyAsync($"Sorry, only the botowner can do this ({botOwner}");
return;
}
redis.Client.StringSet("youtubeKey", key);
await ReplyAsync("Apikey has been set");
}
}
using System.Threading.Tasks;
using Discord.Commands;
using StackExchange.Redis;
namespace Geekbot.net.Modules
{
[Group("admin")]
public class AdminCmd : ModuleBase
{
private readonly IDatabase redis;
public AdminCmd(IDatabase redis)
{
this.redis = redis;
}
[RequireUserPermission(Discord.GuildPermission.Administrator)]
[Command("welcome", RunMode = RunMode.Async), Summary("Set a Welcome Message (use '$user' to mention the new joined user).")]
public async Task SetWelcomeMessage([Remainder, Summary("The message")] string welcomeMessage)
{
var key = Context.Guild.Id + "-welcomeMsg";
redis.StringSet(key, welcomeMessage);
var formatedMessage = welcomeMessage.Replace("$user", Context.User.Mention);
await ReplyAsync("Welcome message has been changed\r\nHere is an example of how it would look:\r\n" +
formatedMessage);
}
[Command("youtubekey", RunMode = RunMode.Async), Summary("Set the youtube api key")]
public async Task SetYoutubeKey([Summary("API Key")] string key)
{
var botOwner = redis.StringGet("botOwner");
if (!Context.User.Id.ToString().Equals(botOwner.ToString()))
{
await ReplyAsync($"Sorry, only the botowner can do this ({botOwner}");
return;
}
redis.StringSet("youtubeKey", key);
await ReplyAsync("Apikey has been set");
}
}
}

View file

@ -1,25 +1,27 @@
using System.Threading.Tasks;
using Discord.Commands;
using Geekbot.net.Lib.IClients;
using RestSharp;
namespace Geekbot.net.Modules
{
public class Cat : ModuleBase
{
private readonly ICatClient catClient;
public Cat(ICatClient catClient)
{
this.catClient = catClient;
}
[Command("cat", RunMode = RunMode.Async), Summary("Return a random image of a cat.")]
public async Task Say()
{
var request = new RestRequest("meow.php", Method.GET);
dynamic response = catClient.Client.Execute<dynamic>(request);
await ReplyAsync(response.Data["file"]);
}
}
using System;
using System.Threading.Tasks;
using Discord.Commands;
using RestSharp;
namespace Geekbot.net.Modules
{
public class Cat : ModuleBase
{
[Command("cat", RunMode = RunMode.Async), Summary("Return a random image of a cat.")]
public async Task Say()
{
var catClient = new RestClient("http://random.cat");
var request = new RestRequest("meow.php", Method.GET);
catClient.ExecuteAsync<CatResponse>(request, async response => {
await ReplyAsync(response.Data.file);
});
}
}
public class CatResponse
{
public string file { get; set; }
}
}

View file

@ -1,24 +1,23 @@
using System;
using System.Threading.Tasks;
using Discord.Commands;
using Geekbot.net.Lib.IClients;
namespace Geekbot.net.Modules
{
public class Choose : ModuleBase
{
private readonly IRandomClient rnd;
public Choose(IRandomClient randomClient)
{
rnd = randomClient;
}
[Command("choose", RunMode = RunMode.Async), Summary("Let the bot make a choice for you.")]
public async Task Command([Remainder, Summary("The choices, sepperated by a ;")] string choices)
{
var choicesArray = choices.Split(';');
var choice = rnd.Client.Next(choicesArray.Length);
await ReplyAsync($"I choose **{choicesArray[choice]}**");
}
}
using System;
using System.Threading.Tasks;
using Discord.Commands;
namespace Geekbot.net.Modules
{
public class Choose : ModuleBase
{
private readonly Random rnd;
public Choose(Random RandomClient)
{
rnd = RandomClient;
}
[Command("choose", RunMode = RunMode.Async), Summary("Let the bot make a choice for you.")]
public async Task Command([Remainder, Summary("The choices, sepperated by a ;")] string choices)
{
var choicesArray = choices.Split(';');
var choice = rnd.Next(choicesArray.Length);
await ReplyAsync($"I choose **{choicesArray[choice]}**");
}
}
}

View file

@ -2,16 +2,16 @@
using System.Threading.Tasks;
using Discord;
using Discord.Commands;
using Geekbot.net.Lib.IClients;
using StackExchange.Redis;
namespace Geekbot.net.Modules
{
public class Counters : ModuleBase
{
private readonly IRedisClient redis;
public Counters(IRedisClient redisClient)
private readonly IDatabase redis;
public Counters(IDatabase redis)
{
redis = redisClient;
this.redis = redis;
}
[Command("good", RunMode = RunMode.Async), Summary("Increase Someones Karma")]
@ -29,11 +29,11 @@ namespace Geekbot.net.Modules
else
{
var key = Context.Guild.Id + "-" + user.Id + "-karma";
var badJokes = (int)redis.Client.StringGet(key);
var badJokes = (int)redis.StringGet(key);
var newBadJokes = badJokes + 1;
redis.Client.StringSet(key, newBadJokes.ToString());
redis.StringSet(key, newBadJokes.ToString());
var lastKey = Context.Guild.Id + "-" + Context.User.Id + "-karma-timeout";
redis.Client.StringSet(lastKey, GetNewLastKarma());
redis.StringSet(lastKey, GetNewLastKarma());
var eb = new EmbedBuilder();
eb.WithAuthor(new EmbedAuthorBuilder()
@ -64,11 +64,11 @@ namespace Geekbot.net.Modules
else
{
var key = Context.Guild.Id + "-" + user.Id + "-karma";
var badJokes = (int)redis.Client.StringGet(key);
var badJokes = (int)redis.StringGet(key);
var newBadJokes = badJokes - 1;
redis.Client.StringSet(key, newBadJokes.ToString());
redis.StringSet(key, newBadJokes.ToString());
var lastKey = Context.Guild.Id + "-" + Context.User.Id + "-karma-timeout";
redis.Client.StringSet(lastKey, GetNewLastKarma());
redis.StringSet(lastKey, GetNewLastKarma());
var eb = new EmbedBuilder();
eb.WithAuthor(new EmbedAuthorBuilder()
@ -87,7 +87,7 @@ namespace Geekbot.net.Modules
private int GetLastKarma()
{
var lastKey = Context.Guild.Id + "-" + Context.User.Id + "-karma-timeout";
var redisReturn = redis.Client.StringGet(lastKey);
var redisReturn = redis.StringGet(lastKey);
if (!int.TryParse(redisReturn.ToString(), out var i))
{
i = GetUnixTimestamp();

View file

@ -1,25 +1,27 @@
using System.Threading.Tasks;
using Discord.Commands;
using Geekbot.net.Lib.IClients;
using RestSharp;
namespace Geekbot.net.Modules
{
public class Dog : ModuleBase
{
private readonly IDogClient dogClient;
public Dog(IDogClient dogClient)
{
this.dogClient = dogClient;
}
[Command("dog", RunMode = RunMode.Async), Summary("Return a random image of a dog.")]
public async Task Say()
{
var request = new RestRequest("woof.json", Method.GET);
dynamic response = dogClient.Client.Execute<dynamic>(request);
await ReplyAsync(response.Data["url"]);
}
}
using System;
using System.Threading.Tasks;
using Discord.Commands;
using RestSharp;
namespace Geekbot.net.Modules
{
public class Dog : ModuleBase
{
[Command("dog", RunMode = RunMode.Async), Summary("Return a random image of a dog.")]
public async Task Say()
{
var dogClient = new RestClient("http://random.dog");
var request = new RestRequest("woof.json", Method.GET);
Console.WriteLine(dogClient.BaseUrl);
dogClient.ExecuteAsync<DogResponse>(request, async response => {
await ReplyAsync(response.Data.url);
});
}
}
public class DogResponse
{
public string url { get; set; }
}
}

View file

@ -2,16 +2,15 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using Discord.Commands;
using Geekbot.net.Lib.IClients;
namespace Geekbot.net.Modules
{
public class EightBall : ModuleBase
{
private readonly IRandomClient rnd;
public EightBall(IRandomClient randomClient)
private readonly Random rnd;
public EightBall(Random RandomClient)
{
rnd = randomClient;
rnd = RandomClient;
}
[Command("8ball", RunMode = RunMode.Async), Summary("Ask 8Ball a Question.")]
public async Task Ball([Remainder, Summary("The Question")] string echo)
@ -38,7 +37,7 @@ namespace Geekbot.net.Modules
"Outlook not so good",
"Very doubtful"};
var answer = rnd.Client.Next(replies.Count);
var answer = rnd.Next(replies.Count);
await ReplyAsync(replies[answer]);
}
}

View file

@ -1,43 +0,0 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Discord.Commands;
using static Geekbot.net.Lib.Dtos.FourChanDto;
using Geekbot.net.Lib.IClients;
namespace Geekbot.net.Modules
{
public class FourChan : ModuleBase
{
[Command("4chan", RunMode = RunMode.Async), Summary("Get Something from 4chan")]
public async Task Chan([Summary("The someone")] string boardParam)
{
try
{
var boards = FourChanBoardClient.Boards();
var board = new Board();
foreach (var b in boards.getBoards())
{
if (b.board.Equals(boardParam))
{
board = b;
break;
}
}
if (board.board == boardParam)
{
await ReplyAsync($"{board.title} - {board.meta_description}");
} else
{
await ReplyAsync("Sorry, that board does not exist...");
}
}
catch (Exception e)
{
await ReplyAsync(e.Message);
}
}
}
}
// var boards = new List<string>["a", "b", "c", "d", "e", "f", "g", "gif", "h", "hr", "k", "m", "o", "p", "r", "s", "t", "u", "v", "vg", "vr", "w", "wg", "i", "ic", "r9k", "s4s", "cm", "hm", "lgbt", "y", "3", "aco", "adv", "an", "asp", "biz", "cgl", "ck", "co", "diy", "fa", "fit", "gd", "hc", "his", "int", "jp", "lit", "mlp", "mu", "n", "news", "out", "po", "pol", "qst", "sci", "soc" / sp / tg / toy / trv / tv / vp / wsg / wsr /];

View file

@ -1,48 +1,48 @@
using System;
using System.Threading.Tasks;
using Discord.Commands;
using Discord;
using Geekbot.net.Lib;
using System.Linq;
using Geekbot.net.Lib.IClients;
namespace Geekbot.net.Modules
{
public class GuildInfo : ModuleBase
{
private readonly IRedisClient redis;
public GuildInfo(IRedisClient redisClient)
{
redis = redisClient;
}
[Command("serverstats", RunMode = RunMode.Async), Summary("Show some info about the bot.")]
public async Task getInfo()
{
var eb = new EmbedBuilder();
eb.WithAuthor(new EmbedAuthorBuilder()
.WithIconUrl(Context.Guild.IconUrl)
.WithName(Context.Guild.Name));
eb.WithColor(new Color(110, 204, 147));
var created = Context.Guild.CreatedAt;
var age = Math.Floor((DateTime.Now - created).TotalDays);
var messages = redis.Client.StringGet($"{Context.Guild.Id}-messages");
var level = LevelCalc.GetLevelAtExperience((int)messages);
eb.AddField("Server Age", $"{created.Day}/{created.Month}/{created.Year} ({age} days)");
eb.AddInlineField("Level", level)
.AddInlineField("Messages", messages);
await ReplyAsync("", false, eb.Build());
}
public static string FirstCharToUpper(string input)
{
if (String.IsNullOrEmpty(input))
throw new ArgumentException("ARGH!");
return input.First().ToString().ToUpper() + input.Substring(1);
}
}
using System;
using System.Threading.Tasks;
using Discord.Commands;
using Discord;
using Geekbot.net.Lib;
using System.Linq;
using StackExchange.Redis;
namespace Geekbot.net.Modules
{
public class GuildInfo : ModuleBase
{
private readonly IDatabase redis;
public GuildInfo(IDatabase redis)
{
this.redis = redis;
}
[Command("serverstats", RunMode = RunMode.Async), Summary("Show some info about the bot.")]
public async Task getInfo()
{
var eb = new EmbedBuilder();
eb.WithAuthor(new EmbedAuthorBuilder()
.WithIconUrl(Context.Guild.IconUrl)
.WithName(Context.Guild.Name));
eb.WithColor(new Color(110, 204, 147));
var created = Context.Guild.CreatedAt;
var age = Math.Floor((DateTime.Now - created).TotalDays);
var messages = redis.StringGet($"{Context.Guild.Id}-messages");
var level = LevelCalc.GetLevelAtExperience((int)messages);
eb.AddField("Server Age", $"{created.Day}/{created.Month}/{created.Year} ({age} days)");
eb.AddInlineField("Level", level)
.AddInlineField("Messages", messages);
await ReplyAsync("", false, eb.Build());
}
public static string FirstCharToUpper(string input)
{
if (String.IsNullOrEmpty(input))
throw new ArgumentException("ARGH!");
return input.First().ToString().ToUpper() + input.Substring(1);
}
}
}

View file

@ -1,34 +1,34 @@
using System.Threading.Tasks;
using Discord;
using Discord.Commands;
using Geekbot.net.Lib.IClients;
namespace Geekbot.net.Modules
{
public class Info : ModuleBase
{
private readonly IRedisClient redis;
public Info(IRedisClient redisClient)
{
redis = redisClient;
}
[Command("info", RunMode = RunMode.Async), Summary("Get Information about the bot")]
public async Task BotInfo()
{
var eb = new EmbedBuilder();
eb.WithTitle("Geekbot V3");
var botOwner = Context.Guild.GetUserAsync(ulong.Parse(redis.Client.StringGet("botOwner"))).Result;
eb.AddInlineField("Status", Context.Client.ConnectionState.ToString())
.AddInlineField("Bot Name", Context.Client.CurrentUser.Username)
.AddInlineField("Bot Owner", $"{botOwner.Username}#{botOwner.Discriminator}");
eb.AddInlineField("Servers", Context.Client.GetGuildsAsync().Result.Count);
await ReplyAsync("", false, eb.Build());
}
}
using System.Threading.Tasks;
using Discord;
using Discord.Commands;
using StackExchange.Redis;
namespace Geekbot.net.Modules
{
public class Info : ModuleBase
{
private readonly IDatabase redis;
public Info(IDatabase redis)
{
this.redis = redis;
}
[Command("info", RunMode = RunMode.Async), Summary("Get Information about the bot")]
public async Task BotInfo()
{
var eb = new EmbedBuilder();
eb.WithTitle("Geekbot V3.1");
var botOwner = Context.Guild.GetUserAsync(ulong.Parse(redis.StringGet("botOwner"))).Result;
eb.AddInlineField("Status", Context.Client.ConnectionState.ToString())
.AddInlineField("Bot Name", Context.Client.CurrentUser.Username)
.AddInlineField("Bot Owner", $"{botOwner.Username}#{botOwner.Discriminator}");
eb.AddInlineField("Servers", Context.Client.GetGuildsAsync().Result.Count);
await ReplyAsync("", false, eb.Build());
}
}
}

View file

@ -1,24 +1,25 @@
using System.Threading.Tasks;
using System;
using System.Threading.Tasks;
using Discord.Commands;
using Geekbot.net.Lib;
using Geekbot.net.Lib.IClients;
using StackExchange.Redis;
namespace Geekbot.net.Modules
{
public class Roll : ModuleBase
{
private readonly IRedisClient redis;
private readonly IRandomClient rnd;
public Roll(IRedisClient redisClient, IRandomClient randomClient)
private readonly IDatabase redis;
private readonly Random rnd;
public Roll(IDatabase redis, Random RandomClient)
{
redis = redisClient;
rnd = randomClient;
this.redis = redis;
this.rnd = RandomClient;
}
[Command("roll", RunMode = RunMode.Async), Summary("Roll a number between 1 and 100.")]
public async Task RollCommand([Remainder, Summary("stuff...")] string stuff = "nothing")
{
var number = rnd.Client.Next(1, 100);
var number = rnd.Next(1, 100);
var guess = 1000;
int.TryParse(stuff, out guess);
if (guess <= 100 && guess > 0)
@ -28,8 +29,8 @@ namespace Geekbot.net.Modules
{
await ReplyAsync($"Congratulations {Context.User.Username}, your guess was correct!");
var key = $"{Context.Guild.Id}-{Context.User.Id}-correctRolls";
var messages = (int)redis.Client.StringGet(key);
redis.Client.StringSet(key, (messages + 1).ToString());
var messages = (int)redis.StringGet(key);
redis.StringSet(key, (messages + 1).ToString());
}
}
else
@ -41,7 +42,7 @@ namespace Geekbot.net.Modules
[Command("dice", RunMode = RunMode.Async), Summary("Roll a dice")]
public async Task DiceCommand([Summary("The highest number on the dice")] int max = 6)
{
var number = rnd.Client.Next(1, max);
var number = rnd.Next(1, max);
await ReplyAsync(Context.Message.Author.Mention + ", you rolled " + number);
}
}

View file

@ -1,97 +1,97 @@
using System;
using System.Threading.Tasks;
using Discord;
using Discord.Commands;
using Geekbot.net.Lib.IClients;
namespace Geekbot.net.Modules
{
public class Ship : ModuleBase
{
private readonly IRedisClient redis;
private readonly IRandomClient rnd;
public Ship(IRedisClient redisClient, IRandomClient randomClient)
{
redis = redisClient;
rnd = randomClient;
}
[Command("Ship", RunMode = RunMode.Async), Summary("Ask the Shipping meter")]
public async Task Command([Summary("User 1")] IUser user1, [Summary("User 2")] IUser user2)
{
// Create a String
var dbstring = "";
if (user1.Id > user2.Id)
{
dbstring = $"{user1.Id}-{user2.Id}";
}
else
{
dbstring = $"{user2.Id}-{user1.Id}";
}
dbstring = $"{Context.Guild.Id}-{dbstring}";
Console.WriteLine(dbstring);
var dbval = redis.Client.StringGet(dbstring);
var shippingRate = 0;
if (dbval.IsNullOrEmpty)
{
shippingRate = rnd.Client.Next(1, 100);
redis.Client.StringSet(dbstring, shippingRate);
}
else
{
shippingRate = int.Parse(dbval.ToString());
}
var reply = ":heartpulse: **Matchmaking** :heartpulse:\r\n";
reply = reply + $":two_hearts: {user1.Mention} :heart: {user2.Mention} :two_hearts:\r\n";
reply = reply + $"0% [{BlockCounter(shippingRate)}] 100% - {DeterminateSuccess(shippingRate)}";
await ReplyAsync(reply);
}
private string DeterminateSuccess(int rate)
{
if (rate < 20)
{
return "Not gonna happen";
} if (rate >= 20 && rate < 40)
{
return "Not such a good idea";
} if (rate >= 40 && rate < 60)
{
return "There might be a chance";
} if (rate >= 60 && rate < 80)
{
return "Almost a match, but could work";
} if (rate >= 80)
{
return "It's a match";
}
return "a";
}
private string BlockCounter(int rate)
{
var amount = Math.Floor(decimal.Floor(rate / 10));
Console.WriteLine(amount);
var blocks = "";
for(int i = 1; i <= 10; i++)
{
if(i <= amount)
{
blocks = blocks + ":white_medium_small_square:";
if(i == amount)
{
blocks = blocks + $" {rate}% ";
}
} else
{
blocks = blocks + ":black_medium_small_square:";
}
}
return blocks;
}
}
using System;
using System.Threading.Tasks;
using Discord;
using Discord.Commands;
using StackExchange.Redis;
namespace Geekbot.net.Modules
{
public class Ship : ModuleBase
{
private readonly IDatabase redis;
private readonly Random rnd;
public Ship(IDatabase redis, Random RandomClient)
{
this.redis = redis;
this.rnd = RandomClient;
}
[Command("Ship", RunMode = RunMode.Async), Summary("Ask the Shipping meter")]
public async Task Command([Summary("User 1")] IUser user1, [Summary("User 2")] IUser user2)
{
// Create a String
var dbstring = "";
if (user1.Id > user2.Id)
{
dbstring = $"{user1.Id}-{user2.Id}";
}
else
{
dbstring = $"{user2.Id}-{user1.Id}";
}
dbstring = $"{Context.Guild.Id}-{dbstring}";
Console.WriteLine(dbstring);
var dbval = redis.StringGet(dbstring);
var shippingRate = 0;
if (dbval.IsNullOrEmpty)
{
shippingRate = rnd.Next(1, 100);
redis.StringSet(dbstring, shippingRate);
}
else
{
shippingRate = int.Parse(dbval.ToString());
}
var reply = ":heartpulse: **Matchmaking** :heartpulse:\r\n";
reply = reply + $":two_hearts: {user1.Mention} :heart: {user2.Mention} :two_hearts:\r\n";
reply = reply + $"0% [{BlockCounter(shippingRate)}] 100% - {DeterminateSuccess(shippingRate)}";
await ReplyAsync(reply);
}
private string DeterminateSuccess(int rate)
{
if (rate < 20)
{
return "Not gonna happen";
} if (rate >= 20 && rate < 40)
{
return "Not such a good idea";
} if (rate >= 40 && rate < 60)
{
return "There might be a chance";
} if (rate >= 60 && rate < 80)
{
return "Almost a match, but could work";
} if (rate >= 80)
{
return "It's a match";
}
return "a";
}
private string BlockCounter(int rate)
{
var amount = Math.Floor(decimal.Floor(rate / 10));
Console.WriteLine(amount);
var blocks = "";
for(int i = 1; i <= 10; i++)
{
if(i <= amount)
{
blocks = blocks + ":white_medium_small_square:";
if(i == amount)
{
blocks = blocks + $" {rate}% ";
}
} else
{
blocks = blocks + ":black_medium_small_square:";
}
}
return blocks;
}
}
}

View file

@ -6,16 +6,16 @@ using System.Linq;
using Discord;
using Discord.Commands;
using Geekbot.net.Lib;
using Geekbot.net.Lib.IClients;
using StackExchange.Redis;
namespace Geekbot.net.Modules
{
public class UserInfo : ModuleBase
{
private readonly IRedisClient redis;
public UserInfo(IRedisClient redisClient)
private readonly IDatabase redis;
public UserInfo(IDatabase redis)
{
redis = redisClient;
this.redis = redis;
}
[Alias("stats")]
@ -27,11 +27,11 @@ namespace Geekbot.net.Modules
var age = Math.Floor((DateTime.Now - userInfo.CreatedAt).TotalDays);
var key = Context.Guild.Id + "-" + userInfo.Id;
var messages = (int)redis.Client.StringGet(key + "-messages");
var messages = (int)redis.StringGet(key + "-messages");
var level = LevelCalc.GetLevelAtExperience(messages);
var guildKey = Context.Guild.Id.ToString();
var guildMessages = (int)redis.Client.StringGet(guildKey + "-messages");
var guildMessages = (int)redis.StringGet(guildKey + "-messages");
var percent = Math.Round((double)(100 * messages) / guildMessages, 2);
@ -47,13 +47,13 @@ namespace Geekbot.net.Modules
.AddInlineField("Messages Sent", messages)
.AddInlineField("Server Total", $"{percent}%");
var karma = redis.Client.StringGet(key + "-karma");
var karma = redis.StringGet(key + "-karma");
if (!karma.IsNullOrEmpty)
{
eb.AddInlineField("Karma", karma);
}
var correctRolls = redis.Client.StringGet($"{Context.Guild.Id}-{userInfo.Id}-correctRolls");
var correctRolls = redis.StringGet($"{Context.Guild.Id}-{userInfo.Id}-correctRolls");
if (!correctRolls.IsNullOrEmpty)
{
eb.AddInlineField("Guessed Rolls", correctRolls);
@ -68,13 +68,13 @@ namespace Geekbot.net.Modules
{
await ReplyAsync("this will take a moment...");
var guildKey = Context.Guild.Id.ToString();
var guildMessages = (int)redis.Client.StringGet(guildKey + "-messages");
var guildMessages = (int)redis.StringGet(guildKey + "-messages");
var allGuildUsers = await Context.Guild.GetUsersAsync();
var unsortedDict = new Dictionary<string, int>();
foreach(var user in allGuildUsers)
{
var key = Context.Guild.Id + "-" + user.Id;
var messages = (int)redis.Client.StringGet(key + "-messages");
var messages = (int)redis.StringGet(key + "-messages");
if(messages > 0) {
unsortedDict.Add($"{user.Username}#{user.Discriminator}", messages);
}

View file

@ -1,56 +1,56 @@
using System;
using System.Threading.Tasks;
using Discord.Commands;
using Geekbot.net.Lib.IClients;
using Google.Apis.Services;
using Google.Apis.YouTube.v3;
namespace Geekbot.net.Modules
{
public class Youtube : ModuleBase
{
private readonly IRedisClient redis;
public Youtube(IRedisClient redisClient)
{
redis = redisClient;
}
[Command("yt", RunMode = RunMode.Async), Summary("Search for something on youtube.")]
public async Task Yt([Remainder, Summary("A Song Title")] string searchQuery)
{
var key = redis.Client.StringGet("youtubeKey");
if (key.IsNullOrEmpty)
{
await ReplyAsync("No youtube key set, please tell my senpai to set one");
return;
}
try
{
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
ApiKey = key.ToString(),
ApplicationName = this.GetType().ToString()
});
var searchListRequest = youtubeService.Search.List("snippet");
searchListRequest.Q = searchQuery;
searchListRequest.MaxResults = 2;
var searchListResponse = await searchListRequest.ExecuteAsync();
var result = searchListResponse.Items[0];
await ReplyAsync(
$"\"{result.Snippet.Title}\" from \"{result.Snippet.ChannelTitle}\" https://youtu.be/{result.Id.VideoId}");
}
catch (Exception e)
{
await ReplyAsync("Something went wrong... informing my senpai...");
var botOwner = Context.Guild.GetUserAsync(ulong.Parse(redis.Client.StringGet("botOwner"))).Result;
var dm = await botOwner.CreateDMChannelAsync();
await dm.SendMessageAsync($"Something went wrong while getting a video from youtube:\r\n```\r\n{e.Message}\r\n```");
}
}
}
using System;
using System.Threading.Tasks;
using Discord.Commands;
using Google.Apis.Services;
using Google.Apis.YouTube.v3;
using StackExchange.Redis;
namespace Geekbot.net.Modules
{
public class Youtube : ModuleBase
{
private readonly IDatabase redis;
public Youtube(IDatabase redis)
{
this.redis = redis;
}
[Command("yt", RunMode = RunMode.Async), Summary("Search for something on youtube.")]
public async Task Yt([Remainder, Summary("A Song Title")] string searchQuery)
{
var key = redis.StringGet("youtubeKey");
if (key.IsNullOrEmpty)
{
await ReplyAsync("No youtube key set, please tell my senpai to set one");
return;
}
try
{
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
ApiKey = key.ToString(),
ApplicationName = this.GetType().ToString()
});
var searchListRequest = youtubeService.Search.List("snippet");
searchListRequest.Q = searchQuery;
searchListRequest.MaxResults = 2;
var searchListResponse = await searchListRequest.ExecuteAsync();
var result = searchListResponse.Items[0];
await ReplyAsync(
$"\"{result.Snippet.Title}\" from \"{result.Snippet.ChannelTitle}\" https://youtu.be/{result.Id.VideoId}");
}
catch (Exception e)
{
await ReplyAsync("Something went wrong... informing my senpai...");
var botOwner = Context.Guild.GetUserAsync(ulong.Parse(redis.StringGet("botOwner"))).Result;
var dm = await botOwner.GetOrCreateDMChannelAsync();
await dm.SendMessageAsync($"Something went wrong while getting a video from youtube:\r\n```\r\n{e.Message}\r\n```");
}
}
}
}

View file

@ -1,13 +1,16 @@
using System;
using System.Reflection;
using System.Runtime.InteropServices.ComTypes;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Discord;
using Discord.Commands;
using Discord.WebSocket;
using Geekbot.net.Lib;
using Geekbot.net.Lib.IClients;
using Geekbot.net.Modules;
using RestSharp;
using StackExchange.Redis;
namespace Geekbot.net
@ -16,9 +19,10 @@ namespace Geekbot.net
{
private CommandService commands;
private DiscordSocketClient client;
private DependencyMap map;
private IRedisClient redis;
private IDatabase redis;
private RedisValue token;
private IServiceCollection services;
private IServiceProvider servicesProvider;
private static void Main(string[] args)
{
@ -30,33 +34,42 @@ namespace Geekbot.net
Console.WriteLine("=========================================");
Console.WriteLine("Starting...");
Task.WaitAll(new Program().MainAsync());
new Program().MainAsync().GetAwaiter().GetResult();
}
public async Task MainAsync()
{
client = new DiscordSocketClient();
commands = new CommandService();
redis = new RedisClient();
token = redis.Client.StringGet("discordToken");
try
{
var redisMultiplexer = ConnectionMultiplexer.Connect("127.0.0.1:6379");
redis = redisMultiplexer.GetDatabase(6);
}
catch (Exception)
{
Console.WriteLine("Start Redis pls...");
Environment.Exit(1);
}
token = redis.StringGet("discordToken");
if (token.IsNullOrEmpty)
{
Console.Write("Your bot Token: ");
var newToken = Console.ReadLine();
redis.Client.StringSet("discordToken", newToken);
redis.StringSet("discordToken", newToken);
token = newToken;
Console.Write("Bot Owner User ID: ");
var ownerId = Console.ReadLine();
redis.Client.StringSet("botOwner", ownerId);
redis.StringSet("botOwner", ownerId);
}
map = new DependencyMap();
map.Add<ICatClient>(new CatClient());
map.Add<IDogClient>(new DogClient());
map.Add(redis);
map.Add<IRandomClient>(new RandomClient());
services = new ServiceCollection();
var RandomClient = new Random();
services.AddSingleton(RandomClient);
services.AddSingleton(redis);
Console.WriteLine("Connecting to Discord...");
@ -83,6 +96,7 @@ namespace Geekbot.net
client.MessageReceived += HandleMessageReceived;
client.UserJoined += HandleUserJoined;
await commands.AddModulesAsync(Assembly.GetEntryAssembly());
servicesProvider = services.BuildServiceProvider();
Console.WriteLine("Done and ready for use...\n");
}
@ -120,14 +134,9 @@ namespace Geekbot.net
await message.Channel.SendMessageAsync("hui!!!");
return;
}
// if (message.ToString().ToLower().Contains("teamspeak") || message.ToString().ToLower().Contains("skype"))
// {
// await message.Channel.SendMessageAsync("How dare you to use such a filthy word in here http://bit.ly/2poL2IZ");
// return;
// }
if (!(message.HasCharPrefix('!', ref argPos) || message.HasMentionPrefix(client.CurrentUser, ref argPos))) return;
var context = new CommandContext(client, message);
Task.Run(async () => await commands.ExecuteAsync(context, argPos, map));
Task.Run(async () => await commands.ExecuteAsync(context, argPos, servicesProvider));
}
public async Task HandleMessageReceived(SocketMessage messsageParam)
@ -140,15 +149,15 @@ namespace Geekbot.net
Console.WriteLine(channel.Guild.Name + " - " + message.Channel + " - " + message.Author.Username + " - " + message.Content);
var statsRecorder = new StatsRecorder(message, redis);
Task.Run(() => statsRecorder.UpdateUserRecordAsync());
Task.Run(() => statsRecorder.UpdateGuildRecordAsync());
Task.Run(async () => await statsRecorder.UpdateUserRecordAsync());
Task.Run(async () => await statsRecorder.UpdateGuildRecordAsync());
}
public async Task HandleUserJoined(SocketGuildUser user)
{
if (!user.IsBot)
{
var message = redis.Client.StringGet(user.Guild.Id + "-welcomeMsg");
var message = redis.StringGet(user.Guild.Id + "-welcomeMsg");
if (!message.IsNullOrEmpty)
{
message = message.ToString().Replace("$user", user.Mention);

BIN
Geekbot.net/derp.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 361 KiB

BIN
derp.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 361 KiB