Merge pull request #981 from Kwoth/dev

Update 1.1.1
This commit is contained in:
Master Kwoth 2017-01-15 16:48:27 +01:00 committed by GitHub
commit e9948009d9
50 changed files with 1922 additions and 285 deletions

@ -1 +1 @@
Subproject commit b9f767337d2b7c07ed76eb83c3bc5030109d5238 Subproject commit e9dca6c648b23bd9e957d8f9eee516df6ce11091

View File

@ -28,15 +28,21 @@ If you entered your Droplets IP address correctly, it should show **login as:**
![img1](https://cdn.discordapp.com/attachments/251504306010849280/251504416019054592/git.gif) ![img1](https://cdn.discordapp.com/attachments/251504306010849280/251504416019054592/git.gif)
Ubuntu:
`sudo apt-get install git -y` `sudo apt-get install git -y`
CentOS:
`yum -y install git`
**NOTE:** If the command is not being initiated, hit **Enter** **NOTE:** If the command is not being initiated, hit **Enter**
####Installing .NET Core SDK ####Installing .NET Core SDK
![img2](https://cdn.discordapp.com/attachments/251504306010849280/251504746987388938/dotnet.gif) ![img2](https://cdn.discordapp.com/attachments/251504306010849280/251504746987388938/dotnet.gif)
Go to [this link](https://www.microsoft.com/net/core#ubuntu) provided by microsoft for instructions on how to get the most up to date version of the dotnet core sdk! Go to [this link](https://www.microsoft.com/net/core#ubuntu) (for Ubuntu) or to [this link](https://www.microsoft.com/net/core#linuxcentos) (for CentOS) provided by microsoft for instructions on how to get the most up to date version of the dotnet core sdk!
Make sure that you're on the correct page for your distribution of linux as the guides are different for the various distributions Make sure that you're on the correct page for your distribution of linux as the guides are different for the various distributions
We'll go over the steps here for Ubuntu 16.04 anyway (these will **only** work on Ubuntu 16.04), accurate as of 25/11/2016 We'll go over the steps here for Ubuntu 16.04 anyway (these will **only** work on Ubuntu 16.04), accurate as of 25/11/2016
@ -53,14 +59,29 @@ sudo apt-get update && sudo apt-get install dotnet-dev-1.0.0-preview2.1-003177 -
![img3](https://cdn.discordapp.com/attachments/251504306010849280/251505294654308353/libopus.gif) ![img3](https://cdn.discordapp.com/attachments/251504306010849280/251505294654308353/libopus.gif)
Ubuntu:
`sudo apt-get install libopus0 opus-tools libopus-dev libsodium-dev -y` `sudo apt-get install libopus0 opus-tools libopus-dev libsodium-dev -y`
CentOS:
`yum -y install opus opus-devel`
####Installing FFMPEG ####Installing FFMPEG
![img4](https://cdn.discordapp.com/attachments/251504306010849280/251505443111829505/ffmpeg.gif) ![img4](https://cdn.discordapp.com/attachments/251504306010849280/251505443111829505/ffmpeg.gif)
Ubuntu:
`apt-get install ffmpeg -y` `apt-get install ffmpeg -y`
Centos:
```
yum -y install http://li.nux.ro/download/nux/dextop/el7/x86_64/nux-dextop-release-0-5.el7.nux.noarch.rpm epel-release
yum -y install ffmpeg
```
**NOTE:** If you are running **UBUNTU 14.04**, you must run these first: **NOTE:** If you are running **UBUNTU 14.04**, you must run these first:
``` ```
@ -74,10 +95,6 @@ sudo apt-get dist-upgrade
**NOTE:** If you are running **Debian 8 Jessie**, please, follow these steps: **NOTE:** If you are running **Debian 8 Jessie**, please, follow these steps:
`wget http://luxcaeli.de/installer.sh && sudo bash installer.sh` *Thanks to Eleria <3*
In case you are not able to install it with **installer**, follow these steps:
``` ```
sudo apt-get update sudo apt-get update
echo "deb http://ftp.debian.org/debian jessie-backports main" | tee /etc/apt/sources.list.d/debian-backports.list echo "deb http://ftp.debian.org/debian jessie-backports main" | tee /etc/apt/sources.list.d/debian-backports.list
@ -88,8 +105,14 @@ sudo apt-get update && sudo apt-get install ffmpeg -y
![img5](https://cdn.discordapp.com/attachments/251504306010849280/251505519758409728/tmux.gif) ![img5](https://cdn.discordapp.com/attachments/251504306010849280/251505519758409728/tmux.gif)
Ubuntu:
`sudo apt-get install tmux -y` `sudo apt-get install tmux -y`
Centos:
`yum -y install tmux`
####Getting NadekoBot ####Getting NadekoBot
Use the following command to get and run `linuxAIO.sh`: Use the following command to get and run `linuxAIO.sh`:

View File

@ -7,12 +7,11 @@ ________________________________________________________________________________
#### Prerequisites #### Prerequisites
- 1) [.NET Core SDK][.NET Core SDK] - 1) [.NET Core SDK][.NET Core SDK]
- 2) [Git][Git] - 2) [Git][Git]
- 3) [FFMPEG][FFMPEG] - 3) Google Account
- 4) Google Account - 4) Soundcloud Account (if you want soundcloud support)
- 5) Soundcloud Account (if you want soundcloud support) - 5) [7zip][7zip] (or whatever you are using, WinRar)
- 6) [7zip][7zip] (or whatever you are using, WinRar) - 6) [Notepad++][Notepad++]
- 7) [Notepad++][Notepad++] - 7) Windows 8 or later
- 8) Windows 8 or later
####Guide ####Guide
- Make sure you have installed both [Git][Git] and the [.NET Core SDK][.NET Core SDK]. - Make sure you have installed both [Git][Git] and the [.NET Core SDK][.NET Core SDK].
@ -80,11 +79,20 @@ ________________________________________________________________________________
- You've updated and are running again, easy as that! - You've updated and are running again, easy as that!
________________________________________________________________________________ ________________________________________________________________________________
#### Setting Up NadekoBot For Music ### Setting Up NadekoBot For Music
##### Prerequisites
- 1) [FFMPEG][FFMPEG] installed.
- 2) Setting up API keys.
In order to have a functioning music module, you need to install ffmpeg and setup api keys.
#### Manual `ffmpeg` setup
- Create a folder named `ffmpeg` in your main Windows directory. We will use **C:\ffmpeg** (for our guide)
- Download FFMPEG through the link https://ffmpeg.zeranoe.com/builds/ (download static build)
- EXTRACT it using `7zip` and place the FOLDER `ffmpeg-xxxxx-git-xxxxx-xxxx-static` inside **C:\ffmpeg**
- Before proceeding, check out this gif to set up `ffmpeg` PATH correctly ![LINK TO gif](http://i.imgur.com/aR5l1Hn.gif) *(thanks to PooPeePants#7135)*
- Go to My Computer, right click and select Properties. On the left tab, select Advanced System Settings. Under the Advanced tab, select Environmental Variables near the bottom. One of the variables should be called "Path". Add a semi-colon (;) to the end followed by your FFMPEG's **bin** install location (**for example C:\ffmpeg\ffmpeg-xxxxx-git-xxxxx-xxxx-static\bin**). Save and close.
- Setup your API keys as explained above.
- **Restart your computer**
#### Api keys setup
- Follow these steps on how to setup Google API keys: - Follow these steps on how to setup Google API keys:
- Go to [Google Console][Google Console] and log in. - Go to [Google Console][Google Console] and log in.
- Create a new project (name does not matter). Once the project is created, go into "Enable and manage APIs." - Create a new project (name does not matter). Once the project is created, go into "Enable and manage APIs."
@ -98,22 +106,12 @@ ________________________________________________________________________________
- Enter a name for the app and create it. - Enter a name for the app and create it.
- You will need to fill out an application form to request access to the Soundcloud API. - You will need to fill out an application form to request access to the Soundcloud API.
- All requests for an API key must go through the review process, where applications will be reviewed on a case by case basis, in line with Soundcloud API Terms of Use. If your application is successful, you will receive an API key. - All requests for an API key must go through the review process, where applications will be reviewed on a case by case basis, in line with Soundcloud API Terms of Use. If your application is successful, you will receive an API key.
- **Restart your computer**. - **Restart your computer**
####Manual `ffmpeg` setup
**Do this step in case you were not able to install `ffmpeg` with the installer.**
- Create a folder named `ffmpeg` in your main Windows directory. We will use **C:\ffmpeg** (for our guide)
- Download FFMPEG through the link https://ffmpeg.zeranoe.com/builds/ (download static build)
- Extract it using `7zip` and place the folder `ffmpeg-xxxxx-git-xxxxx-xxxx-static` inside **C:\ffmpeg**
- Before proceeding, check out this gif to set up `ffmpeg` PATH correctly ![LINK TO gif](http://i.imgur.com/aR5l1Hn.gif) *(thanks to PooPeePants#7135)*
- Go to My Computer, right click and select Properties. On the left tab, select Advanced System Settings. Under the Advanced tab, select Environmental Variables near the bottom. One of the variables should be called "Path". Add a semi-colon (;) to the end followed by your FFMPEG's **bin** install location (**for example C:\ffmpeg\ffmpeg-xxxxx-git-xxxxx-xxxx-static\bin**). Save and close.
- Setup your API keys as explained above.
- Restart your computer.
[.NET Core SDK]: https://www.microsoft.com/net/core#windowscmd [.NET Core SDK]: https://www.microsoft.com/net/core#windowscmd
[Git]: https://git-scm.com/download/win [Git]: https://git-scm.com/download/win
[FFMPEG]: https://github.com/Soundofdarkness/FFMPEG-Inst/releases
[7zip]: http://www.7-zip.org/download.html [7zip]: http://www.7-zip.org/download.html
[DiscordApp]: https://discordapp.com/developers/applications/me [DiscordApp]: https://discordapp.com/developers/applications/me
[Notepad++]: https://notepad-plus-plus.org/ [Notepad++]: https://notepad-plus-plus.org/

View File

@ -1,2 +0,0 @@
Docs are in the air.
Kwoth is magic.

View File

@ -0,0 +1,984 @@
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using NadekoBot.Services.Database;
using NadekoBot.Services.Database.Models;
using NadekoBot.Modules.Music.Classes;
namespace NadekoBot.Migrations
{
[DbContext(typeof(NadekoContext))]
[Migration("20170112185538_currency-modifications")]
partial class currencymodifications
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "1.1.0-rtm-22752");
modelBuilder.Entity("NadekoBot.Services.Database.Models.AntiRaidSetting", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("Action");
b.Property<int>("GuildConfigId");
b.Property<int>("Seconds");
b.Property<int>("UserThreshold");
b.HasKey("Id");
b.HasIndex("GuildConfigId")
.IsUnique();
b.ToTable("AntiRaidSetting");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.AntiSpamIgnore", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int?>("AntiSpamSettingId");
b.Property<ulong>("ChannelId");
b.HasKey("Id");
b.HasIndex("AntiSpamSettingId");
b.ToTable("AntiSpamIgnore");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.AntiSpamSetting", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("Action");
b.Property<int>("GuildConfigId");
b.Property<int>("MessageThreshold");
b.HasKey("Id");
b.HasIndex("GuildConfigId")
.IsUnique();
b.ToTable("AntiSpamSetting");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.BlacklistItem", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int?>("BotConfigId");
b.Property<ulong>("ItemId");
b.Property<int>("Type");
b.HasKey("Id");
b.HasIndex("BotConfigId");
b.ToTable("BlacklistItem");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.BotConfig", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<float>("BetflipMultiplier");
b.Property<float>("Betroll100Multiplier");
b.Property<float>("Betroll67Multiplier");
b.Property<float>("Betroll91Multiplier");
b.Property<ulong>("BufferSize");
b.Property<int>("CurrencyDropAmount");
b.Property<float>("CurrencyGenerationChance");
b.Property<int>("CurrencyGenerationCooldown");
b.Property<string>("CurrencyName");
b.Property<string>("CurrencyPluralName");
b.Property<string>("CurrencySign");
b.Property<string>("DMHelpString");
b.Property<bool>("ForwardMessages");
b.Property<bool>("ForwardToAllOwners");
b.Property<string>("HelpString");
b.Property<int>("MigrationVersion");
b.Property<int>("MinimumBetAmount");
b.Property<string>("RemindMessageFormat");
b.Property<bool>("RotatingStatuses");
b.Property<int>("TriviaCurrencyReward");
b.HasKey("Id");
b.ToTable("BotConfig");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.ClashCaller", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<bool>("BaseDestroyed");
b.Property<string>("CallUser");
b.Property<int>("ClashWarId");
b.Property<int?>("SequenceNumber");
b.Property<int>("Stars");
b.Property<DateTime>("TimeAdded");
b.HasKey("Id");
b.HasIndex("ClashWarId");
b.ToTable("ClashCallers");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.ClashWar", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<ulong>("ChannelId");
b.Property<string>("EnemyClan");
b.Property<ulong>("GuildId");
b.Property<int>("Size");
b.Property<DateTime>("StartedAt");
b.Property<int>("WarState");
b.HasKey("Id");
b.ToTable("ClashOfClans");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.CommandCooldown", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("CommandName");
b.Property<int?>("GuildConfigId");
b.Property<int>("Seconds");
b.HasKey("Id");
b.HasIndex("GuildConfigId");
b.ToTable("CommandCooldown");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.CommandPrice", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int?>("BotConfigId");
b.Property<string>("CommandName");
b.Property<int>("Price");
b.HasKey("Id");
b.HasIndex("BotConfigId");
b.HasIndex("Price")
.IsUnique();
b.ToTable("CommandPrice");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.ConvertUnit", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("InternalTrigger");
b.Property<decimal>("Modifier");
b.Property<string>("UnitType");
b.HasKey("Id");
b.ToTable("ConversionUnits");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.Currency", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<long>("Amount");
b.Property<ulong>("UserId");
b.HasKey("Id");
b.HasIndex("UserId")
.IsUnique();
b.ToTable("Currency");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.CurrencyTransaction", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<long>("Amount");
b.Property<string>("Reason");
b.Property<ulong>("UserId");
b.HasKey("Id");
b.ToTable("CurrencyTransactions");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.CustomReaction", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<ulong?>("GuildId");
b.Property<bool>("IsRegex");
b.Property<bool>("OwnerOnly");
b.Property<string>("Response");
b.Property<string>("Trigger");
b.HasKey("Id");
b.ToTable("CustomReactions");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.Donator", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("Amount");
b.Property<string>("Name");
b.Property<ulong>("UserId");
b.HasKey("Id");
b.HasIndex("UserId")
.IsUnique();
b.ToTable("Donators");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.EightBallResponse", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int?>("BotConfigId");
b.Property<string>("Text");
b.HasKey("Id");
b.HasIndex("BotConfigId");
b.ToTable("EightBallResponses");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.FilterChannelId", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<ulong>("ChannelId");
b.Property<int?>("GuildConfigId");
b.Property<int?>("GuildConfigId1");
b.HasKey("Id");
b.HasIndex("GuildConfigId");
b.HasIndex("GuildConfigId1");
b.ToTable("FilterChannelId");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.FilteredWord", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int?>("GuildConfigId");
b.Property<string>("Word");
b.HasKey("Id");
b.HasIndex("GuildConfigId");
b.ToTable("FilteredWord");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.FollowedStream", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<ulong>("ChannelId");
b.Property<int?>("GuildConfigId");
b.Property<ulong>("GuildId");
b.Property<int>("Type");
b.Property<string>("Username");
b.HasKey("Id");
b.HasIndex("GuildConfigId");
b.ToTable("FollowedStream");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.GCChannelId", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<ulong>("ChannelId");
b.Property<int?>("GuildConfigId");
b.HasKey("Id");
b.HasIndex("GuildConfigId");
b.ToTable("GCChannelId");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.GuildConfig", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<ulong>("AutoAssignRoleId");
b.Property<bool>("AutoDeleteByeMessages");
b.Property<int>("AutoDeleteByeMessagesTimer");
b.Property<bool>("AutoDeleteGreetMessages");
b.Property<int>("AutoDeleteGreetMessagesTimer");
b.Property<bool>("AutoDeleteSelfAssignedRoleMessages");
b.Property<ulong>("ByeMessageChannelId");
b.Property<string>("ChannelByeMessageText");
b.Property<string>("ChannelGreetMessageText");
b.Property<bool>("CleverbotEnabled");
b.Property<float>("DefaultMusicVolume");
b.Property<bool>("DeleteMessageOnCommand");
b.Property<string>("DmGreetMessageText");
b.Property<bool>("ExclusiveSelfAssignedRoles");
b.Property<bool>("FilterInvites");
b.Property<bool>("FilterWords");
b.Property<ulong>("GreetMessageChannelId");
b.Property<ulong>("GuildId");
b.Property<int?>("LogSettingId");
b.Property<string>("MuteRoleName");
b.Property<string>("PermissionRole");
b.Property<int?>("RootPermissionId");
b.Property<bool>("SendChannelByeMessage");
b.Property<bool>("SendChannelGreetMessage");
b.Property<bool>("SendDmGreetMessage");
b.Property<bool>("VerbosePermissions");
b.Property<bool>("VoicePlusTextEnabled");
b.HasKey("Id");
b.HasIndex("GuildId")
.IsUnique();
b.HasIndex("LogSettingId");
b.HasIndex("RootPermissionId");
b.ToTable("GuildConfigs");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.GuildRepeater", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<ulong>("ChannelId");
b.Property<int?>("GuildConfigId");
b.Property<ulong>("GuildId");
b.Property<TimeSpan>("Interval");
b.Property<string>("Message");
b.HasKey("Id");
b.HasIndex("GuildConfigId");
b.ToTable("GuildRepeater");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.IgnoredLogChannel", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<ulong>("ChannelId");
b.Property<int?>("LogSettingId");
b.HasKey("Id");
b.HasIndex("LogSettingId");
b.ToTable("IgnoredLogChannels");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.IgnoredVoicePresenceChannel", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<ulong>("ChannelId");
b.Property<int?>("LogSettingId");
b.HasKey("Id");
b.HasIndex("LogSettingId");
b.ToTable("IgnoredVoicePresenceCHannels");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.LogSetting", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<bool>("ChannelCreated");
b.Property<ulong?>("ChannelCreatedId");
b.Property<bool>("ChannelDestroyed");
b.Property<ulong?>("ChannelDestroyedId");
b.Property<ulong>("ChannelId");
b.Property<bool>("ChannelUpdated");
b.Property<ulong?>("ChannelUpdatedId");
b.Property<bool>("IsLogging");
b.Property<ulong?>("LogOtherId");
b.Property<bool>("LogUserPresence");
b.Property<ulong?>("LogUserPresenceId");
b.Property<bool>("LogVoicePresence");
b.Property<ulong?>("LogVoicePresenceId");
b.Property<ulong?>("LogVoicePresenceTTSId");
b.Property<bool>("MessageDeleted");
b.Property<ulong?>("MessageDeletedId");
b.Property<bool>("MessageUpdated");
b.Property<ulong?>("MessageUpdatedId");
b.Property<bool>("UserBanned");
b.Property<ulong?>("UserBannedId");
b.Property<bool>("UserJoined");
b.Property<ulong?>("UserJoinedId");
b.Property<bool>("UserLeft");
b.Property<ulong?>("UserLeftId");
b.Property<ulong?>("UserMutedId");
b.Property<ulong>("UserPresenceChannelId");
b.Property<bool>("UserUnbanned");
b.Property<ulong?>("UserUnbannedId");
b.Property<bool>("UserUpdated");
b.Property<ulong?>("UserUpdatedId");
b.Property<ulong>("VoicePresenceChannelId");
b.HasKey("Id");
b.ToTable("LogSettings");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.ModulePrefix", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int?>("BotConfigId");
b.Property<string>("ModuleName");
b.Property<string>("Prefix");
b.HasKey("Id");
b.HasIndex("BotConfigId");
b.ToTable("ModulePrefixes");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.MusicPlaylist", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Author");
b.Property<ulong>("AuthorId");
b.Property<string>("Name");
b.HasKey("Id");
b.ToTable("MusicPlaylists");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.MutedUserId", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int?>("GuildConfigId");
b.Property<ulong>("UserId");
b.HasKey("Id");
b.HasIndex("GuildConfigId");
b.ToTable("MutedUserId");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.Permission", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int?>("NextId");
b.Property<int>("PrimaryTarget");
b.Property<ulong>("PrimaryTargetId");
b.Property<int>("SecondaryTarget");
b.Property<string>("SecondaryTargetName");
b.Property<bool>("State");
b.HasKey("Id");
b.HasIndex("NextId")
.IsUnique();
b.ToTable("Permission");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.PlayingStatus", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int?>("BotConfigId");
b.Property<string>("Status");
b.HasKey("Id");
b.HasIndex("BotConfigId");
b.ToTable("PlayingStatus");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.PlaylistSong", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int?>("MusicPlaylistId");
b.Property<string>("Provider");
b.Property<int>("ProviderType");
b.Property<string>("Query");
b.Property<string>("Title");
b.Property<string>("Uri");
b.HasKey("Id");
b.HasIndex("MusicPlaylistId");
b.ToTable("PlaylistSong");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.Quote", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<ulong>("AuthorId");
b.Property<string>("AuthorName")
.IsRequired();
b.Property<ulong>("GuildId");
b.Property<string>("Keyword")
.IsRequired();
b.Property<string>("Text")
.IsRequired();
b.HasKey("Id");
b.ToTable("Quotes");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.RaceAnimal", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int?>("BotConfigId");
b.Property<string>("Icon");
b.Property<string>("Name");
b.HasKey("Id");
b.HasIndex("BotConfigId");
b.ToTable("RaceAnimals");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.Reminder", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<ulong>("ChannelId");
b.Property<bool>("IsPrivate");
b.Property<string>("Message");
b.Property<ulong>("ServerId");
b.Property<ulong>("UserId");
b.Property<DateTime>("When");
b.HasKey("Id");
b.ToTable("Reminders");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.SelfAssignedRole", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<ulong>("GuildId");
b.Property<ulong>("RoleId");
b.HasKey("Id");
b.HasIndex("GuildId", "RoleId")
.IsUnique();
b.ToTable("SelfAssignableRoles");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.UserPokeTypes", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<ulong>("UserId");
b.Property<string>("type");
b.HasKey("Id");
b.HasIndex("UserId")
.IsUnique();
b.ToTable("PokeGame");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.AntiRaidSetting", b =>
{
b.HasOne("NadekoBot.Services.Database.Models.GuildConfig", "GuildConfig")
.WithOne("AntiRaidSetting")
.HasForeignKey("NadekoBot.Services.Database.Models.AntiRaidSetting", "GuildConfigId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.AntiSpamIgnore", b =>
{
b.HasOne("NadekoBot.Services.Database.Models.AntiSpamSetting")
.WithMany("IgnoredChannels")
.HasForeignKey("AntiSpamSettingId");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.AntiSpamSetting", b =>
{
b.HasOne("NadekoBot.Services.Database.Models.GuildConfig", "GuildConfig")
.WithOne("AntiSpamSetting")
.HasForeignKey("NadekoBot.Services.Database.Models.AntiSpamSetting", "GuildConfigId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.BlacklistItem", b =>
{
b.HasOne("NadekoBot.Services.Database.Models.BotConfig")
.WithMany("Blacklist")
.HasForeignKey("BotConfigId");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.ClashCaller", b =>
{
b.HasOne("NadekoBot.Services.Database.Models.ClashWar", "ClashWar")
.WithMany("Bases")
.HasForeignKey("ClashWarId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.CommandCooldown", b =>
{
b.HasOne("NadekoBot.Services.Database.Models.GuildConfig")
.WithMany("CommandCooldowns")
.HasForeignKey("GuildConfigId");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.CommandPrice", b =>
{
b.HasOne("NadekoBot.Services.Database.Models.BotConfig")
.WithMany("CommandPrices")
.HasForeignKey("BotConfigId");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.EightBallResponse", b =>
{
b.HasOne("NadekoBot.Services.Database.Models.BotConfig")
.WithMany("EightBallResponses")
.HasForeignKey("BotConfigId");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.FilterChannelId", b =>
{
b.HasOne("NadekoBot.Services.Database.Models.GuildConfig")
.WithMany("FilterInvitesChannelIds")
.HasForeignKey("GuildConfigId");
b.HasOne("NadekoBot.Services.Database.Models.GuildConfig")
.WithMany("FilterWordsChannelIds")
.HasForeignKey("GuildConfigId1");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.FilteredWord", b =>
{
b.HasOne("NadekoBot.Services.Database.Models.GuildConfig")
.WithMany("FilteredWords")
.HasForeignKey("GuildConfigId");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.FollowedStream", b =>
{
b.HasOne("NadekoBot.Services.Database.Models.GuildConfig")
.WithMany("FollowedStreams")
.HasForeignKey("GuildConfigId");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.GCChannelId", b =>
{
b.HasOne("NadekoBot.Services.Database.Models.GuildConfig")
.WithMany("GenerateCurrencyChannelIds")
.HasForeignKey("GuildConfigId");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.GuildConfig", b =>
{
b.HasOne("NadekoBot.Services.Database.Models.LogSetting", "LogSetting")
.WithMany()
.HasForeignKey("LogSettingId");
b.HasOne("NadekoBot.Services.Database.Models.Permission", "RootPermission")
.WithMany()
.HasForeignKey("RootPermissionId");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.GuildRepeater", b =>
{
b.HasOne("NadekoBot.Services.Database.Models.GuildConfig")
.WithMany("GuildRepeaters")
.HasForeignKey("GuildConfigId");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.IgnoredLogChannel", b =>
{
b.HasOne("NadekoBot.Services.Database.Models.LogSetting", "LogSetting")
.WithMany("IgnoredChannels")
.HasForeignKey("LogSettingId");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.IgnoredVoicePresenceChannel", b =>
{
b.HasOne("NadekoBot.Services.Database.Models.LogSetting", "LogSetting")
.WithMany("IgnoredVoicePresenceChannelIds")
.HasForeignKey("LogSettingId");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.ModulePrefix", b =>
{
b.HasOne("NadekoBot.Services.Database.Models.BotConfig")
.WithMany("ModulePrefixes")
.HasForeignKey("BotConfigId");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.MutedUserId", b =>
{
b.HasOne("NadekoBot.Services.Database.Models.GuildConfig")
.WithMany("MutedUsers")
.HasForeignKey("GuildConfigId");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.Permission", b =>
{
b.HasOne("NadekoBot.Services.Database.Models.Permission", "Next")
.WithOne("Previous")
.HasForeignKey("NadekoBot.Services.Database.Models.Permission", "NextId");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.PlayingStatus", b =>
{
b.HasOne("NadekoBot.Services.Database.Models.BotConfig")
.WithMany("RotatingStatusMessages")
.HasForeignKey("BotConfigId");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.PlaylistSong", b =>
{
b.HasOne("NadekoBot.Services.Database.Models.MusicPlaylist")
.WithMany("Songs")
.HasForeignKey("MusicPlaylistId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.RaceAnimal", b =>
{
b.HasOne("NadekoBot.Services.Database.Models.BotConfig")
.WithMany("RaceAnimals")
.HasForeignKey("BotConfigId");
});
}
}
}

View File

@ -0,0 +1,120 @@
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore.Migrations;
namespace NadekoBot.Migrations
{
public partial class currencymodifications : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<float>(
name: "BetflipMultiplier",
table: "BotConfig",
nullable: false,
defaultValue: 1.8f);
migrationBuilder.AddColumn<float>(
name: "Betroll100Multiplier",
table: "BotConfig",
nullable: false,
defaultValue: 10f);
migrationBuilder.AddColumn<float>(
name: "Betroll67Multiplier",
table: "BotConfig",
nullable: false,
defaultValue: 2f);
migrationBuilder.AddColumn<float>(
name: "Betroll91Multiplier",
table: "BotConfig",
nullable: false,
defaultValue: 3f);
migrationBuilder.AddColumn<int>(
name: "CurrencyDropAmount",
table: "BotConfig",
nullable: false,
defaultValue: 1);
migrationBuilder.AddColumn<int>(
name: "MinimumBetAmount",
table: "BotConfig",
nullable: false,
defaultValue: 3);
migrationBuilder.AddColumn<int>(
name: "TriviaCurrencyReward",
table: "BotConfig",
nullable: false,
defaultValue: 0);
migrationBuilder.CreateTable(
name: "CommandPrice",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("Sqlite:Autoincrement", true),
BotConfigId = table.Column<int>(nullable: true),
CommandName = table.Column<string>(nullable: true),
Price = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_CommandPrice", x => x.Id);
table.ForeignKey(
name: "FK_CommandPrice_BotConfig_BotConfigId",
column: x => x.BotConfigId,
principalTable: "BotConfig",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateIndex(
name: "IX_CommandPrice_BotConfigId",
table: "CommandPrice",
column: "BotConfigId");
migrationBuilder.CreateIndex(
name: "IX_CommandPrice_Price",
table: "CommandPrice",
column: "Price",
unique: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "CommandPrice");
migrationBuilder.DropColumn(
name: "BetflipMultiplier",
table: "BotConfig");
migrationBuilder.DropColumn(
name: "Betroll100Multiplier",
table: "BotConfig");
migrationBuilder.DropColumn(
name: "Betroll67Multiplier",
table: "BotConfig");
migrationBuilder.DropColumn(
name: "Betroll91Multiplier",
table: "BotConfig");
migrationBuilder.DropColumn(
name: "CurrencyDropAmount",
table: "BotConfig");
migrationBuilder.DropColumn(
name: "MinimumBetAmount",
table: "BotConfig");
migrationBuilder.DropColumn(
name: "TriviaCurrencyReward",
table: "BotConfig");
}
}
}

View File

@ -4,8 +4,6 @@ using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Migrations;
using NadekoBot.Services.Database; using NadekoBot.Services.Database;
using NadekoBot.Services.Database.Models;
using NadekoBot.Modules.Music.Classes;
namespace NadekoBot.Migrations namespace NadekoBot.Migrations
{ {
@ -96,8 +94,18 @@ namespace NadekoBot.Migrations
b.Property<int>("Id") b.Property<int>("Id")
.ValueGeneratedOnAdd(); .ValueGeneratedOnAdd();
b.Property<float>("BetflipMultiplier");
b.Property<float>("Betroll100Multiplier");
b.Property<float>("Betroll67Multiplier");
b.Property<float>("Betroll91Multiplier");
b.Property<ulong>("BufferSize"); b.Property<ulong>("BufferSize");
b.Property<int>("CurrencyDropAmount");
b.Property<float>("CurrencyGenerationChance"); b.Property<float>("CurrencyGenerationChance");
b.Property<int>("CurrencyGenerationCooldown"); b.Property<int>("CurrencyGenerationCooldown");
@ -118,10 +126,14 @@ namespace NadekoBot.Migrations
b.Property<int>("MigrationVersion"); b.Property<int>("MigrationVersion");
b.Property<int>("MinimumBetAmount");
b.Property<string>("RemindMessageFormat"); b.Property<string>("RemindMessageFormat");
b.Property<bool>("RotatingStatuses"); b.Property<bool>("RotatingStatuses");
b.Property<int>("TriviaCurrencyReward");
b.HasKey("Id"); b.HasKey("Id");
b.ToTable("BotConfig"); b.ToTable("BotConfig");
@ -191,6 +203,27 @@ namespace NadekoBot.Migrations
b.ToTable("CommandCooldown"); b.ToTable("CommandCooldown");
}); });
modelBuilder.Entity("NadekoBot.Services.Database.Models.CommandPrice", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int?>("BotConfigId");
b.Property<string>("CommandName");
b.Property<int>("Price");
b.HasKey("Id");
b.HasIndex("BotConfigId");
b.HasIndex("Price")
.IsUnique();
b.ToTable("CommandPrice");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.ConvertUnit", b => modelBuilder.Entity("NadekoBot.Services.Database.Models.ConvertUnit", b =>
{ {
b.Property<int>("Id") b.Property<int>("Id")
@ -823,6 +856,13 @@ namespace NadekoBot.Migrations
.HasForeignKey("GuildConfigId"); .HasForeignKey("GuildConfigId");
}); });
modelBuilder.Entity("NadekoBot.Services.Database.Models.CommandPrice", b =>
{
b.HasOne("NadekoBot.Services.Database.Models.BotConfig")
.WithMany("CommandPrices")
.HasForeignKey("BotConfigId");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.EightBallResponse", b => modelBuilder.Entity("NadekoBot.Services.Database.Models.EightBallResponse", b =>
{ {
b.HasOne("NadekoBot.Services.Database.Models.BotConfig") b.HasOne("NadekoBot.Services.Database.Models.BotConfig")

View File

@ -25,11 +25,11 @@ namespace NadekoBot.Modules.Administration
{ {
private const string clockEmojiUrl = "https://cdn.discordapp.com/attachments/155726317222887425/258309524966866945/clock.png"; private const string clockEmojiUrl = "https://cdn.discordapp.com/attachments/155726317222887425/258309524966866945/clock.png";
private static ShardedDiscordClient _client { get; } private static DiscordShardedClient _client { get; }
private static Logger _log { get; } private static Logger _log { get; }
private static string prettyCurrentTime => $"【{DateTime.Now:HH:mm:ss}】"; private static string prettyCurrentTime => $"【{DateTime.Now:HH:mm:ss}】";
private static string currentTime = $"{DateTime.Now:HH:mm:ss}"; private static string currentTime => $"{DateTime.Now:HH:mm:ss}";
public static ConcurrentDictionary<ulong, LogSetting> GuildLogSettings { get; } public static ConcurrentDictionary<ulong, LogSetting> GuildLogSettings { get; }
@ -81,7 +81,7 @@ namespace NadekoBot.Modules.Administration
_client.UserPresenceUpdated += _client_UserPresenceUpdated; _client.UserPresenceUpdated += _client_UserPresenceUpdated;
_client.UserVoiceStateUpdated += _client_UserVoiceStateUpdated; _client.UserVoiceStateUpdated += _client_UserVoiceStateUpdated;
_client.UserVoiceStateUpdated += _client_UserVoiceStateUpdated_TTS; _client.UserVoiceStateUpdated += _client_UserVoiceStateUpdated_TTS;
_client.GuildUserUpdated += _client_GuildUserUpdated; _client.GuildMemberUpdated += _client_GuildUserUpdated;
#if !GLOBAL_NADEKO #if !GLOBAL_NADEKO
_client.UserUpdated += _client_UserUpdated; _client.UserUpdated += _client_UserUpdated;
#endif #endif
@ -94,7 +94,7 @@ namespace NadekoBot.Modules.Administration
MuteCommands.UserUnmuted += MuteCommands_UserUnmuted; MuteCommands.UserUnmuted += MuteCommands_UserUnmuted;
} }
private static async void _client_UserUpdated(SocketUser before, SocketUser uAfter) private static async Task _client_UserUpdated(SocketUser before, SocketUser uAfter)
{ {
try try
{ {
@ -162,7 +162,7 @@ namespace NadekoBot.Modules.Administration
{ } { }
} }
private static async void _client_UserVoiceStateUpdated_TTS(SocketUser iusr, SocketVoiceState before, SocketVoiceState after) private static async Task _client_UserVoiceStateUpdated_TTS(SocketUser iusr, SocketVoiceState before, SocketVoiceState after)
{ {
try try
{ {
@ -317,7 +317,7 @@ namespace NadekoBot.Modules.Administration
catch { } catch { }
} }
private static async void _client_GuildUserUpdated(SocketGuildUser before, SocketGuildUser after) private static async Task _client_GuildUserUpdated(SocketGuildUser before, SocketGuildUser after)
{ {
try try
{ {
@ -360,7 +360,7 @@ namespace NadekoBot.Modules.Administration
catch { } catch { }
} }
private static async void _client_ChannelUpdated(IChannel cbefore, IChannel cafter) private static async Task _client_ChannelUpdated(IChannel cbefore, IChannel cafter)
{ {
try try
{ {
@ -403,7 +403,7 @@ namespace NadekoBot.Modules.Administration
catch { } catch { }
} }
private static async void _client_ChannelDestroyed(IChannel ich) private static async Task _client_ChannelDestroyed(IChannel ich)
{ {
try try
{ {
@ -430,7 +430,7 @@ namespace NadekoBot.Modules.Administration
catch { } catch { }
} }
private static async void _client_ChannelCreated(IChannel ich) private static async Task _client_ChannelCreated(IChannel ich)
{ {
try try
{ {
@ -456,7 +456,7 @@ namespace NadekoBot.Modules.Administration
catch (Exception ex) { _log.Warn(ex); } catch (Exception ex) { _log.Warn(ex); }
} }
private static async void _client_UserVoiceStateUpdated(SocketUser iusr, SocketVoiceState before, SocketVoiceState after) private static async Task _client_UserVoiceStateUpdated(SocketUser iusr, SocketVoiceState before, SocketVoiceState after)
{ {
try try
{ {
@ -498,7 +498,7 @@ namespace NadekoBot.Modules.Administration
catch { } catch { }
} }
private static async void _client_UserPresenceUpdated(Optional<SocketGuild> optGuild, SocketUser usr, SocketPresence before, SocketPresence after) private static async Task _client_UserPresenceUpdated(Optional<SocketGuild> optGuild, SocketUser usr, SocketPresence before, SocketPresence after)
{ {
try try
{ {
@ -532,7 +532,7 @@ namespace NadekoBot.Modules.Administration
catch { } catch { }
} }
private static async void _client_UserLeft(IGuildUser usr) private static async Task _client_UserLeft(IGuildUser usr)
{ {
try try
{ {
@ -556,7 +556,7 @@ namespace NadekoBot.Modules.Administration
catch { } catch { }
} }
private static async void _client_UserJoined(IGuildUser usr) private static async Task _client_UserJoined(IGuildUser usr)
{ {
try try
{ {
@ -580,7 +580,7 @@ namespace NadekoBot.Modules.Administration
catch (Exception ex) { _log.Warn(ex); } catch (Exception ex) { _log.Warn(ex); }
} }
private static async void _client_UserUnbanned(IUser usr, IGuild guild) private static async Task _client_UserUnbanned(IUser usr, IGuild guild)
{ {
try try
{ {
@ -604,7 +604,7 @@ namespace NadekoBot.Modules.Administration
catch (Exception ex) { _log.Warn(ex); } catch (Exception ex) { _log.Warn(ex); }
} }
private static async void _client_UserBanned(IUser usr, IGuild guild) private static async Task _client_UserBanned(IUser usr, IGuild guild)
{ {
try try
{ {
@ -627,7 +627,7 @@ namespace NadekoBot.Modules.Administration
catch (Exception ex) { _log.Warn(ex); } catch (Exception ex) { _log.Warn(ex); }
} }
private static async void _client_MessageDeleted(ulong arg1, Optional<SocketMessage> imsg) private static async Task _client_MessageDeleted(ulong arg1, Optional<SocketMessage> imsg)
{ {
try try
@ -664,7 +664,7 @@ namespace NadekoBot.Modules.Administration
catch { } catch { }
} }
private static async void _client_MessageUpdated(Optional<SocketMessage> optmsg, SocketMessage imsg2) private static async Task _client_MessageUpdated(Optional<SocketMessage> optmsg, SocketMessage imsg2)
{ {
try try
{ {

View File

@ -89,54 +89,66 @@ namespace NadekoBot.Modules.Administration
db.Open(); db.Open();
var com = db.CreateCommand(); var com = db.CreateCommand();
com.CommandText = "SELECT * FROM Announcement";
var reader = com.ExecuteReader();
var i = 0; var i = 0;
while (reader.Read()) try
{ {
var gid = (ulong)(long)reader["ServerId"]; com.CommandText = "SELECT * FROM Announcement";
var greet = (long)reader["Greet"] == 1;
var greetDM = (long)reader["GreetPM"] == 1;
var greetChannel = (ulong)(long)reader["GreetChannelId"];
var greetMsg = (string)reader["GreetText"];
var bye = (long)reader["Bye"] == 1;
var byeDM = (long)reader["ByePM"] == 1;
var byeChannel = (ulong)(long)reader["ByeChannelId"];
var byeMsg = (string)reader["ByeText"];
var grdel = false;
var byedel = grdel;
var gc = uow.GuildConfigs.For(gid, set => set);
if (greetDM) var reader = com.ExecuteReader();
gc.SendDmGreetMessage = greet; while (reader.Read())
else {
gc.SendChannelGreetMessage = greet; var gid = (ulong)(long)reader["ServerId"];
gc.GreetMessageChannelId = greetChannel; var greet = (long)reader["Greet"] == 1;
gc.ChannelGreetMessageText = greetMsg; var greetDM = (long)reader["GreetPM"] == 1;
var greetChannel = (ulong)(long)reader["GreetChannelId"];
var greetMsg = (string)reader["GreetText"];
var bye = (long)reader["Bye"] == 1;
var byeDM = (long)reader["ByePM"] == 1;
var byeChannel = (ulong)(long)reader["ByeChannelId"];
var byeMsg = (string)reader["ByeText"];
var grdel = false;
var byedel = grdel;
var gc = uow.GuildConfigs.For(gid, set => set);
gc.SendChannelByeMessage = bye; if (greetDM)
gc.ByeMessageChannelId = byeChannel; gc.SendDmGreetMessage = greet;
gc.ChannelByeMessageText = byeMsg; else
gc.SendChannelGreetMessage = greet;
gc.GreetMessageChannelId = greetChannel;
gc.ChannelGreetMessageText = greetMsg;
gc.AutoDeleteGreetMessagesTimer = gc.AutoDeleteByeMessagesTimer = grdel ? 30 : 0; gc.SendChannelByeMessage = bye;
_log.Info(++i); gc.ByeMessageChannelId = byeChannel;
gc.ChannelByeMessageText = byeMsg;
gc.AutoDeleteGreetMessagesTimer = gc.AutoDeleteByeMessagesTimer = grdel ? 30 : 0;
_log.Info(++i);
}
}
catch {
_log.Warn("Greet/bye messages won't be migrated");
} }
var com2 = db.CreateCommand(); var com2 = db.CreateCommand();
com.CommandText = "SELECT * FROM CurrencyState GROUP BY UserId"; com.CommandText = "SELECT * FROM CurrencyState GROUP BY UserId";
i = 0; i = 0;
var reader2 = com.ExecuteReader(); try
while (reader2.Read())
{ {
_log.Info(++i); var reader2 = com.ExecuteReader();
var curr = new Currency() while (reader2.Read())
{ {
Amount = (long)reader2["Value"], _log.Info(++i);
UserId = (ulong)(long)reader2["UserId"] var curr = new Currency()
}; {
uow.Currency.Add(curr); Amount = (long)reader2["Value"],
UserId = (ulong)(long)reader2["UserId"]
};
uow.Currency.Add(curr);
}
}
catch
{
_log.Warn("Currency won't be migrated");
} }
db.Close(); db.Close();
try { File.Move("data/nadekobot.sqlite", "data/DELETE_ME_nadekobot.sqlite"); } catch { } try { File.Move("data/nadekobot.sqlite", "data/DELETE_ME_nadekobot.sqlite"); } catch { }

View File

@ -37,7 +37,6 @@ namespace NadekoBot.Modules.Administration
static MuteCommands() static MuteCommands()
{ {
var _log = LogManager.GetCurrentClassLogger(); var _log = LogManager.GetCurrentClassLogger();
var sw = Stopwatch.StartNew();
var configs = NadekoBot.AllGuildConfigs; var configs = NadekoBot.AllGuildConfigs;
GuildMuteRoles = new ConcurrentDictionary<ulong, string>(configs GuildMuteRoles = new ConcurrentDictionary<ulong, string>(configs
@ -50,12 +49,9 @@ namespace NadekoBot.Modules.Administration
)); ));
NadekoBot.Client.UserJoined += Client_UserJoined; NadekoBot.Client.UserJoined += Client_UserJoined;
sw.Stop();
_log.Debug($"Loaded in {sw.Elapsed.TotalSeconds:F2}s");
} }
private static async void Client_UserJoined(IGuildUser usr) private static async Task Client_UserJoined(IGuildUser usr)
{ {
try try
{ {

View File

@ -50,7 +50,7 @@ namespace NadekoBot.Modules.Administration
if (string.IsNullOrWhiteSpace(status)) if (string.IsNullOrWhiteSpace(status))
continue; continue;
PlayingPlaceholders.ForEach(e => status = status.Replace(e.Key, e.Value())); PlayingPlaceholders.ForEach(e => status = status.Replace(e.Key, e.Value()));
await NadekoBot.Client.SetGame(status); await NadekoBot.Client.SetGameAsync(status).ConfigureAwait(false);
} }
} }
catch (Exception ex) catch (Exception ex)
@ -67,7 +67,7 @@ namespace NadekoBot.Modules.Administration
public static Dictionary<string, Func<string>> PlayingPlaceholders { get; } = public static Dictionary<string, Func<string>> PlayingPlaceholders { get; } =
new Dictionary<string, Func<string>> { new Dictionary<string, Func<string>> {
{"%servers%", () => NadekoBot.Client.GetGuildsCount().ToString()}, {"%servers%", () => NadekoBot.Client.GetGuildCount().ToString()},
{"%users%", () => NadekoBot.Client.GetGuilds().Sum(s => s.Users.Count).ToString()}, {"%users%", () => NadekoBot.Client.GetGuilds().Sum(s => s.Users.Count).ToString()},
{"%playing%", () => { {"%playing%", () => {
var cnt = Music.Music.MusicPlayers.Count(kvp => kvp.Value.CurrentSong != null); var cnt = Music.Music.MusicPlayers.Count(kvp => kvp.Value.CurrentSong != null);

View File

@ -28,7 +28,7 @@ namespace NadekoBot.Modules.Administration
await Context.Channel.SendErrorAsync("⚠️ Cannot find that server").ConfigureAwait(false); await Context.Channel.SendErrorAsync("⚠️ Cannot find that server").ConfigureAwait(false);
return; return;
} }
if (server.OwnerId != NadekoBot.Client.CurrentUser().Id) if (server.OwnerId != NadekoBot.Client.CurrentUser.Id)
{ {
await server.LeaveAsync().ConfigureAwait(false); await server.LeaveAsync().ConfigureAwait(false);
await Context.Channel.SendConfirmAsync("✅ Left server " + server.Name).ConfigureAwait(false); await Context.Channel.SendConfirmAsync("✅ Left server " + server.Name).ConfigureAwait(false);
@ -57,7 +57,7 @@ namespace NadekoBot.Modules.Administration
if (string.IsNullOrWhiteSpace(newName)) if (string.IsNullOrWhiteSpace(newName))
return; return;
await NadekoBot.Client.CurrentUser().ModifyAsync(u => u.Username = newName).ConfigureAwait(false); await NadekoBot.Client.CurrentUser.ModifyAsync(u => u.Username = newName).ConfigureAwait(false);
await Context.Channel.SendConfirmAsync($"Bot name changed to **{newName}**").ConfigureAwait(false); await Context.Channel.SendConfirmAsync($"Bot name changed to **{newName}**").ConfigureAwait(false);
} }
@ -66,7 +66,7 @@ namespace NadekoBot.Modules.Administration
[OwnerOnly] [OwnerOnly]
public async Task SetStatus([Remainder] SettableUserStatus status) public async Task SetStatus([Remainder] SettableUserStatus status)
{ {
await NadekoBot.Client.SetStatus(status); await NadekoBot.Client.SetStatusAsync(SettableUserStatusToUserStatus(status)).ConfigureAwait(false);
await Context.Channel.SendConfirmAsync($"Bot status changed to **{status}**").ConfigureAwait(false); await Context.Channel.SendConfirmAsync($"Bot status changed to **{status}**").ConfigureAwait(false);
} }
@ -86,7 +86,7 @@ namespace NadekoBot.Modules.Administration
await sr.CopyToAsync(imgStream); await sr.CopyToAsync(imgStream);
imgStream.Position = 0; imgStream.Position = 0;
await NadekoBot.Client.CurrentUser().ModifyAsync(u => u.Avatar = new Image(imgStream)).ConfigureAwait(false); await NadekoBot.Client.CurrentUser.ModifyAsync(u => u.Avatar = new Image(imgStream)).ConfigureAwait(false);
} }
} }
@ -97,7 +97,7 @@ namespace NadekoBot.Modules.Administration
[OwnerOnly] [OwnerOnly]
public async Task SetGame([Remainder] string game = null) public async Task SetGame([Remainder] string game = null)
{ {
await NadekoBot.Client.SetGame(game).ConfigureAwait(false); await NadekoBot.Client.SetGameAsync(game).ConfigureAwait(false);
await Context.Channel.SendConfirmAsync("👾 **New game set.**").ConfigureAwait(false); await Context.Channel.SendConfirmAsync("👾 **New game set.**").ConfigureAwait(false);
} }
@ -108,7 +108,7 @@ namespace NadekoBot.Modules.Administration
{ {
name = name ?? ""; name = name ?? "";
await NadekoBot.Client.SetStream(name, url).ConfigureAwait(false); await NadekoBot.Client.SetGameAsync(name, url, StreamType.Twitch).ConfigureAwait(false);
await Context.Channel.SendConfirmAsync(" **New stream set.**").ConfigureAwait(false); await Context.Channel.SendConfirmAsync(" **New stream set.**").ConfigureAwait(false);
} }
@ -169,6 +169,23 @@ namespace NadekoBot.Modules.Administration
await Context.Channel.SendConfirmAsync("🆗").ConfigureAwait(false); await Context.Channel.SendConfirmAsync("🆗").ConfigureAwait(false);
} }
private static UserStatus SettableUserStatusToUserStatus(SettableUserStatus sus)
{
switch (sus)
{
case SettableUserStatus.Online:
return UserStatus.Online;
case SettableUserStatus.Invisible:
return UserStatus.Invisible;
case SettableUserStatus.Idle:
return UserStatus.AFK;
case SettableUserStatus.Dnd:
return UserStatus.DoNotDisturb;
}
return UserStatus.Online;
}
} }
} }
} }

View File

@ -26,7 +26,7 @@ namespace NadekoBot.Modules.Administration
_log = LogManager.GetCurrentClassLogger(); _log = LogManager.GetCurrentClassLogger();
} }
//todo optimize ASAP //todo optimize ASAP
private static async void UserLeft(IGuildUser user) private static async Task UserLeft(IGuildUser user)
{ {
try try
{ {
@ -58,7 +58,7 @@ namespace NadekoBot.Modules.Administration
catch { } catch { }
} }
private static async void UserJoined(IGuildUser user) private static async Task UserJoined(IGuildUser user)
{ {
try try
{ {

View File

@ -36,7 +36,7 @@ namespace NadekoBot.Modules.Administration
_log.Debug($"Loaded in {sw.Elapsed.TotalSeconds:F2}s"); _log.Debug($"Loaded in {sw.Elapsed.TotalSeconds:F2}s");
} }
private static async void UserUpdatedEventHandler(SocketUser iuser, SocketVoiceState before, SocketVoiceState after) private static async Task UserUpdatedEventHandler(SocketUser iuser, SocketVoiceState before, SocketVoiceState after)
{ {
var user = (iuser as SocketGuildUser); var user = (iuser as SocketGuildUser);
var guild = user?.Guild; var guild = user?.Guild;

View File

@ -18,7 +18,7 @@ namespace NadekoBot.Modules.CustomReactions
public static Dictionary<string, Func<IUserMessage, string>> placeholders = new Dictionary<string, Func<IUserMessage, string>>() public static Dictionary<string, Func<IUserMessage, string>> placeholders = new Dictionary<string, Func<IUserMessage, string>>()
{ {
{"%mention%", (ctx) => { return $"<@{NadekoBot.Client.CurrentUser().Id}>"; } }, {"%mention%", (ctx) => { return $"<@{NadekoBot.Client.CurrentUser.Id}>"; } },
{"%user%", (ctx) => { return ctx.Author.Mention; } }, {"%user%", (ctx) => { return ctx.Author.Mention; } },
{"%rnduser%", (ctx) => { {"%rnduser%", (ctx) => {
var ch = ctx.Channel as ITextChannel; var ch = ctx.Channel as ITextChannel;

View File

@ -207,15 +207,15 @@ namespace NadekoBot.Modules.Gambling
} }
private void Client_MessageReceived(SocketMessage imsg) private Task Client_MessageReceived(SocketMessage imsg)
{ {
var msg = imsg as SocketUserMessage; var msg = imsg as SocketUserMessage;
if (msg == null) if (msg == null)
return; return Task.CompletedTask;
if (msg.IsAuthor() || !(imsg.Channel is ITextChannel) || imsg.Channel != raceChannel) if (msg.IsAuthor() || !(imsg.Channel is ITextChannel) || imsg.Channel != raceChannel)
return; return Task.CompletedTask;
messagesSinceGameStarted++; messagesSinceGameStarted++;
return; return Task.CompletedTask;
} }
private async Task CheckForFullGameAsync(CancellationToken cancelToken) private async Task CheckForFullGameAsync(CancellationToken cancelToken)

View File

@ -0,0 +1,67 @@
using Discord;
using Discord.Commands;
using NadekoBot.Attributes;
using NadekoBot.Extensions;
using NadekoBot.Services;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NadekoBot.Modules.Gambling
{
public partial class Gambling
{
[Group]
public class CurrencyEvents : ModuleBase
{
public enum CurrencyEvent
{
FlowerReaction
}
//flower reaction event
public static readonly ConcurrentHashSet<ulong> _flowerReactionAwardedUsers = new ConcurrentHashSet<ulong>();
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
[OwnerOnly]
public async Task StartEvent(CurrencyEvent e)
{
var channel = (ITextChannel)Context.Channel;
switch (e)
{
case CurrencyEvent.FlowerReaction:
await FlowerReactionEvent(Context).ConfigureAwait(false);
break;
default:
break;
}
}
public static async Task FlowerReactionEvent(CommandContext Context)
{
var msg = await Context.Channel.SendConfirmAsync("Flower reaction event started!",
"Add 🌸 reaction to this message to get 100" + NadekoBot.BotConfig.CurrencySign,
footer: "This event is active for 24 hours.")
.ConfigureAwait(false);
await msg.AddReactionAsync("🌸").ConfigureAwait(false);
using (msg.OnReaction(async (r) =>
{
if (r.Emoji.Name == "🌸" && r.User.IsSpecified && _flowerReactionAwardedUsers.Add(r.User.Value.Id))
{
try { await CurrencyHandler.AddCurrencyAsync(r.User.Value, "Flower Reaction Event", 100, true).ConfigureAwait(false); } catch { }
}
}))
{
await Task.Delay(TimeSpan.FromHours(24)).ConfigureAwait(false);
try { await msg.DeleteAsync().ConfigureAwait(false); } catch { }
_flowerReactionAwardedUsers.Clear();
}
}
}
}
}

View File

@ -53,9 +53,9 @@ namespace NadekoBot.Modules.Gambling
if (guessStr != "H" && guessStr != "T" && guessStr != "HEADS" && guessStr != "TAILS") if (guessStr != "H" && guessStr != "T" && guessStr != "HEADS" && guessStr != "TAILS")
return; return;
if (amount < 3) if (amount < NadekoBot.BotConfig.MinimumBetAmount)
{ {
await Context.Channel.SendErrorAsync($"You can't bet less than 3{CurrencySign}.") await Context.Channel.SendErrorAsync($"You can't bet less than {NadekoBot.BotConfig.MinimumBetAmount}{CurrencySign}.")
.ConfigureAwait(false); .ConfigureAwait(false);
return; return;
} }
@ -84,7 +84,7 @@ namespace NadekoBot.Modules.Gambling
string str; string str;
if (isHeads == result) if (isHeads == result)
{ {
var toWin = (int)Math.Round(amount * 1.8); var toWin = (int)Math.Round(amount * NadekoBot.BotConfig.BetflipMultiplier);
str = $"{Context.User.Mention}`You guessed it!` You won {toWin}{CurrencySign}"; str = $"{Context.User.Mention}`You guessed it!` You won {toWin}{CurrencySign}";
await CurrencyHandler.AddCurrencyAsync(Context.User, "Betflip Gamble", toWin, false).ConfigureAwait(false); await CurrencyHandler.AddCurrencyAsync(Context.User, "Betflip Gamble", toWin, false).ConfigureAwait(false);
} }

View File

@ -173,18 +173,18 @@ namespace NadekoBot.Modules.Gambling
} }
else if (rng < 91) else if (rng < 91)
{ {
str += $"Congratulations! You won {amount * 2}{CurrencySign} for rolling above 66"; str += $"Congratulations! You won {amount * NadekoBot.BotConfig.Betroll67Multiplier}{CurrencySign} for rolling above 66";
await CurrencyHandler.AddCurrencyAsync(Context.User, "Betroll Gamble", amount * 2, false).ConfigureAwait(false); await CurrencyHandler.AddCurrencyAsync(Context.User, "Betroll Gamble", (int)(amount * NadekoBot.BotConfig.Betroll67Multiplier), false).ConfigureAwait(false);
} }
else if (rng < 100) else if (rng < 100)
{ {
str += $"Congratulations! You won {amount * 3}{CurrencySign} for rolling above 90."; str += $"Congratulations! You won {amount * NadekoBot.BotConfig.Betroll91Multiplier}{CurrencySign} for rolling above 90.";
await CurrencyHandler.AddCurrencyAsync(Context.User, "Betroll Gamble", amount * 3, false).ConfigureAwait(false); await CurrencyHandler.AddCurrencyAsync(Context.User, "Betroll Gamble", (int)(amount * NadekoBot.BotConfig.Betroll91Multiplier), false).ConfigureAwait(false);
} }
else else
{ {
str += $"👑 Congratulations! You won {amount * 10}{CurrencySign} for rolling **100**. 👑"; str += $"👑 Congratulations! You won {amount * NadekoBot.BotConfig.Betroll100Multiplier}{CurrencySign} for rolling **100**. 👑";
await CurrencyHandler.AddCurrencyAsync(Context.User, "Betroll Gamble", amount * 10, false).ConfigureAwait(false); await CurrencyHandler.AddCurrencyAsync(Context.User, "Betroll Gamble", (int)(amount * NadekoBot.BotConfig.Betroll100Multiplier), false).ConfigureAwait(false);
} }
await Context.Channel.SendConfirmAsync(str).ConfigureAwait(false); await Context.Channel.SendConfirmAsync(str).ConfigureAwait(false);

View File

@ -168,7 +168,7 @@ namespace NadekoBot.Modules.Games
await End().ConfigureAwait(false); await End().ConfigureAwait(false);
} }
private async void PotentialAcro(SocketMessage arg) private async Task PotentialAcro(SocketMessage arg)
{ {
try try
{ {

View File

@ -58,7 +58,7 @@ namespace NadekoBot.Modules.Games
if (!CleverbotGuilds.TryGetValue(channel.Guild.Id, out cleverbot)) if (!CleverbotGuilds.TryGetValue(channel.Guild.Id, out cleverbot))
return false; return false;
var nadekoId = NadekoBot.Client.CurrentUser().Id; var nadekoId = NadekoBot.Client.CurrentUser.Id;
var normalMention = $"<@{nadekoId}> "; var normalMention = $"<@{nadekoId}> ";
var nickMention = $"<@!{nadekoId}> "; var nickMention = $"<@!{nadekoId}> ";
string message; string message;

View File

@ -45,7 +45,7 @@ namespace NadekoBot.Modules.Games.Commands.Hangman
HangmanObject[] termTypes; HangmanObject[] termTypes;
data.TryGetValue(type, out termTypes); data.TryGetValue(type, out termTypes);
if (termTypes.Length == 0) if (termTypes == null || termTypes.Length == 0)
return null; return null;
return termTypes[rng.Next(0, termTypes.Length)]; return termTypes[rng.Next(0, termTypes.Length)];
@ -114,7 +114,7 @@ namespace NadekoBot.Modules.Games.Commands.Hangman
await GameChannel.EmbedAsync(embed.WithOkColor()).ConfigureAwait(false); await GameChannel.EmbedAsync(embed.WithOkColor()).ConfigureAwait(false);
} }
private async void PotentialGuess(SocketMessage msg) private async Task PotentialGuess(SocketMessage msg)
{ {
try try
{ {

View File

@ -51,7 +51,7 @@ namespace NadekoBot.Modules.Games
.SelectMany(c => c.GenerateCurrencyChannelIds.Select(obj => obj.ChannelId))); .SelectMany(c => c.GenerateCurrencyChannelIds.Select(obj => obj.ChannelId)));
} }
private static async void PotentialFlowerGeneration(SocketMessage imsg) private static async Task PotentialFlowerGeneration(SocketMessage imsg)
{ {
try try
{ {
@ -78,14 +78,32 @@ namespace NadekoBot.Modules.Games
{ {
lastGenerations.AddOrUpdate(channel.Id, DateTime.Now, (id, old) => DateTime.Now); lastGenerations.AddOrUpdate(channel.Id, DateTime.Now, (id, old) => DateTime.Now);
var sent = await channel.SendFileAsync( var dropAmount = NadekoBot.BotConfig.CurrencyDropAmount;
File.Open(GetRandomCurrencyImagePath(), FileMode.OpenOrCreate),
"RandomFlower.jpg",
$"❗ A random { NadekoBot.BotConfig.CurrencyName } appeared! Pick it up by typing `{NadekoBot.ModulePrefixes[typeof(Games).Name]}pick`")
.ConfigureAwait(false);
plantedFlowers.AddOrUpdate(channel.Id, new List<IUserMessage>() { sent }, (id, old) => { old.Add(sent); return old; });
if (dropAmount > 0)
{
var msgs = new IUserMessage[dropAmount];
string firstPart;
if (dropAmount == 1)
{
firstPart = $"A random { NadekoBot.BotConfig.CurrencyName } appeared!";
}
else
{
firstPart = $"{dropAmount} random { NadekoBot.BotConfig.CurrencyPluralName } appeared!";
}
var sent = await channel.SendFileAsync(
File.Open(GetRandomCurrencyImagePath(), FileMode.OpenOrCreate),
"RandomFlower.jpg",
$"❗ {firstPart} Pick it up by typing `{NadekoBot.ModulePrefixes[typeof(Games).Name]}pick`")
.ConfigureAwait(false);
msgs[0] = sent;
plantedFlowers.AddOrUpdate(channel.Id, msgs.ToList(), (id, old) => { old.AddRange(msgs); return old; });
}
} }
} }
catch { } catch { }
@ -108,11 +126,11 @@ namespace NadekoBot.Modules.Games
List<IUserMessage> msgs; List<IUserMessage> msgs;
try { await Context.Message.DeleteAsync().ConfigureAwait(false); } catch { } try { await Context.Message.DeleteAsync().ConfigureAwait(false); } catch { }
if (!plantedFlowers.TryRemove(channel.Id, out msgs)) if (!plantedFlowers.TryRemove(channel.Id, out msgs))
return; return;
await Task.WhenAll(msgs.Select(toDelete => toDelete.DeleteAsync())).ConfigureAwait(false); await Task.WhenAll(msgs.Where(m => m != null).Select(toDelete => toDelete.DeleteAsync())).ConfigureAwait(false);
await CurrencyHandler.AddCurrencyAsync((IGuildUser)Context.User, $"Picked {NadekoBot.BotConfig.CurrencyPluralName}", msgs.Count, false).ConfigureAwait(false); await CurrencyHandler.AddCurrencyAsync((IGuildUser)Context.User, $"Picked {NadekoBot.BotConfig.CurrencyPluralName}", msgs.Count, false).ConfigureAwait(false);
var msg = await channel.SendConfirmAsync($"**{Context.User}** picked {msgs.Count}{NadekoBot.BotConfig.CurrencySign}!").ConfigureAwait(false); var msg = await channel.SendConfirmAsync($"**{Context.User}** picked {msgs.Count}{NadekoBot.BotConfig.CurrencySign}!").ConfigureAwait(false);

View File

@ -153,7 +153,7 @@ namespace NadekoBot.Modules.Games
await originalMessage.Channel.EmbedAsync(GetStats("POLL CLOSED")).ConfigureAwait(false); await originalMessage.Channel.EmbedAsync(GetStats("POLL CLOSED")).ConfigureAwait(false);
} }
private async void Vote(SocketMessage imsg) private async Task Vote(SocketMessage imsg)
{ {
try try
{ {

View File

@ -106,7 +106,7 @@ namespace NadekoBot.Modules.Games
NadekoBot.Client.MessageReceived += AnswerReceived; NadekoBot.Client.MessageReceived += AnswerReceived;
} }
private async void AnswerReceived(SocketMessage imsg) private async Task AnswerReceived(SocketMessage imsg)
{ {
try try
{ {

View File

@ -2,6 +2,7 @@
using Discord.Net; using Discord.Net;
using Discord.WebSocket; using Discord.WebSocket;
using NadekoBot.Extensions; using NadekoBot.Extensions;
using NadekoBot.Services;
using NLog; using NLog;
using System; using System;
using System.Collections.Concurrent; using System.Collections.Concurrent;
@ -55,7 +56,9 @@ namespace NadekoBot.Modules.Games.Trivia
// load question // load question
CurrentQuestion = TriviaQuestionPool.Instance.GetRandomQuestion(oldQuestions); CurrentQuestion = TriviaQuestionPool.Instance.GetRandomQuestion(oldQuestions);
if (CurrentQuestion == null) if (CurrentQuestion == null ||
string.IsNullOrWhiteSpace(CurrentQuestion.Answer) ||
string.IsNullOrWhiteSpace(CurrentQuestion.Question))
{ {
await channel.SendErrorAsync("Trivia Game", "Failed loading a question.").ConfigureAwait(false); await channel.SendErrorAsync("Trivia Game", "Failed loading a question.").ConfigureAwait(false);
return; return;
@ -73,7 +76,9 @@ namespace NadekoBot.Modules.Games.Trivia
questionMessage = await channel.EmbedAsync(questionEmbed).ConfigureAwait(false); questionMessage = await channel.EmbedAsync(questionEmbed).ConfigureAwait(false);
} }
catch (HttpException ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound || ex.StatusCode == System.Net.HttpStatusCode.Forbidden) catch (HttpException ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound ||
ex.StatusCode == System.Net.HttpStatusCode.Forbidden ||
ex.StatusCode == System.Net.HttpStatusCode.BadRequest)
{ {
return; return;
} }
@ -142,7 +147,7 @@ namespace NadekoBot.Modules.Games.Trivia
try { await channel.SendConfirmAsync("Trivia Game", "Stopping after this question.").ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); } try { await channel.SendConfirmAsync("Trivia Game", "Stopping after this question.").ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); }
} }
private async void PotentialGuess(SocketMessage imsg) private async Task PotentialGuess(SocketMessage imsg)
{ {
try try
{ {
@ -177,7 +182,10 @@ namespace NadekoBot.Modules.Games.Trivia
if (Users[guildUser] == WinRequirement) if (Users[guildUser] == WinRequirement)
{ {
ShouldStopGame = true; ShouldStopGame = true;
await channel.SendConfirmAsync("Trivia Game", $"{guildUser.Mention} guessed it and WON the game! The answer was: **{CurrentQuestion.Answer}**").ConfigureAwait(false); try { await channel.SendConfirmAsync("Trivia Game", $"{guildUser.Mention} guessed it and WON the game! The answer was: **{CurrentQuestion.Answer}**").ConfigureAwait(false); } catch { }
var reward = NadekoBot.BotConfig.TriviaCurrencyReward;
if (reward > 0)
await CurrencyHandler.AddCurrencyAsync(guildUser, "Won trivia", reward, true).ConfigureAwait(false);
return; return;
} }
await channel.SendConfirmAsync("Trivia Game", $"{guildUser.Mention} guessed it! The answer was: **{CurrentQuestion.Answer}**").ConfigureAwait(false); await channel.SendConfirmAsync("Trivia Game", $"{guildUser.Mention} guessed it! The answer was: **{CurrentQuestion.Answer}**").ConfigureAwait(false);

View File

@ -80,7 +80,7 @@ namespace NadekoBot.Modules.Games
else if ((pick == 0 && nadekoPick == 1) || else if ((pick == 0 && nadekoPick == 1) ||
(pick == 1 && nadekoPick == 2) || (pick == 1 && nadekoPick == 2) ||
(pick == 2 && nadekoPick == 0)) (pick == 2 && nadekoPick == 0))
msg = $"{NadekoBot.Client.CurrentUser().Mention} won! {GetRPSPick(nadekoPick)} beats {GetRPSPick(pick)}"; msg = $"{NadekoBot.Client.CurrentUser.Mention} won! {GetRPSPick(nadekoPick)} beats {GetRPSPick(pick)}";
else else
msg = $"{Context.User.Mention} won! {GetRPSPick(pick)} beats {GetRPSPick(nadekoPick)}"; msg = $"{Context.User.Mention} won! {GetRPSPick(pick)} beats {GetRPSPick(nadekoPick)}";

View File

@ -137,7 +137,7 @@ namespace NadekoBot.Modules.Help
} }
helpstr.AppendLine($"{string.Join(" ", com.Aliases.Select(a => "`" + a + "`"))} | {string.Format(com.Summary, com.Module.GetPrefix())} {GetCommandRequirements(com)} | {string.Format(com.Remarks, com.Module.GetPrefix())}"); helpstr.AppendLine($"{string.Join(" ", com.Aliases.Select(a => "`" + a + "`"))} | {string.Format(com.Summary, com.Module.GetPrefix())} {GetCommandRequirements(com)} | {string.Format(com.Remarks, com.Module.GetPrefix())}");
} }
helpstr = helpstr.Replace(NadekoBot.Client.CurrentUser().Username , "@BotName"); helpstr = helpstr.Replace(NadekoBot.Client.CurrentUser.Username , "@BotName");
File.WriteAllText("../../docs/Commands List.md", helpstr.ToString()); File.WriteAllText("../../docs/Commands List.md", helpstr.ToString());
await Context.Channel.SendConfirmAsync("Commandlist Regenerated").ConfigureAwait(false); await Context.Channel.SendConfirmAsync("Commandlist Regenerated").ConfigureAwait(false);
} }
@ -161,7 +161,7 @@ namespace NadekoBot.Modules.Help
await channel.SendConfirmAsync( await channel.SendConfirmAsync(
$@"You can support the NadekoBot project on patreon. <https://patreon.com/nadekobot> or $@"You can support the NadekoBot project on patreon. <https://patreon.com/nadekobot> or
You can send donations to `nadekodiscordbot@gmail.com` Paypal <https://paypal.me/Kwoth>
Don't forget to leave your discord name or id in the message. Don't forget to leave your discord name or id in the message.
**Thank you** ").ConfigureAwait(false); **Thank you** ").ConfigureAwait(false);

View File

@ -140,9 +140,15 @@ namespace NadekoBot.Modules.Music.Classes
RemoveSongAt(index, true); RemoveSongAt(index, true);
OnStarted(this, CurrentSong); OnStarted(this, CurrentSong);
await CurrentSong.Play(audioClient, cancelToken); try
{
await CurrentSong.Play(audioClient, cancelToken);
}
catch(OperationCanceledException)
{
OnCompleted(this, CurrentSong);
}
OnCompleted(this, CurrentSong);
if (RepeatPlaylist) if (RepeatPlaylist)
AddSong(CurrentSong, CurrentSong.QueuerName); AddSong(CurrentSong, CurrentSong.QueuerName);
@ -151,7 +157,6 @@ namespace NadekoBot.Modules.Music.Classes
AddSong(CurrentSong, 0); AddSong(CurrentSong, 0);
} }
catch (OperationCanceledException) { }
catch (Exception ex) catch (Exception ex)
{ {
Console.WriteLine("Music thread almost crashed."); Console.WriteLine("Music thread almost crashed.");
@ -337,13 +342,13 @@ namespace NadekoBot.Modules.Music.Classes
}); });
} }
public Task MoveToVoiceChannel(IVoiceChannel voiceChannel) //public async Task MoveToVoiceChannel(IVoiceChannel voiceChannel)
{ //{
if (audioClient?.ConnectionState != ConnectionState.Connected) // if (audioClient?.ConnectionState != ConnectionState.Connected)
throw new InvalidOperationException("Can't move while bot is not connected to voice channel."); // throw new InvalidOperationException("Can't move while bot is not connected to voice channel.");
PlaybackVoiceChannel = voiceChannel; // PlaybackVoiceChannel = voiceChannel;
return PlaybackVoiceChannel.ConnectAsync(); // audioClient = await voiceChannel.ConnectAsync().ConfigureAwait(false);
} //}
public bool ToggleRepeatSong() => this.RepeatSong = !this.RepeatSong; public bool ToggleRepeatSong() => this.RepeatSong = !this.RepeatSong;

View File

@ -47,13 +47,23 @@ namespace NadekoBot.Modules.Music.Classes
public string PrettyFullTime => PrettyCurrentTime + " / " + PrettyTotalTime; public string PrettyFullTime => PrettyCurrentTime + " / " + PrettyTotalTime;
public string PrettyName => $"**[{SongInfo.Title.TrimTo(65)}]({songUrl})**"; public string PrettyName => $"**[{SongInfo.Title.TrimTo(65)}]({songUrl})**";
public string PrettyInfo => $"{MusicPlayer.PrettyVolume} | {PrettyTotalTime} | {PrettyProvider} | {QueuerName}"; public string PrettyInfo => $"{MusicPlayer.PrettyVolume} | {PrettyTotalTime} | {PrettyProvider} | {QueuerName}";
public string PrettyFullName => $"{PrettyName}\n\t\t`{PrettyTotalTime} | {PrettyProvider} | {QueuerName}`"; public string PrettyFullName => $"{PrettyName}\n\t\t`{PrettyTotalTime} | {PrettyProvider} | {QueuerName}`";
public string PrettyCurrentTime => CurrentTime.ToString(@"mm\:ss"); public string PrettyCurrentTime {
get {
var time = CurrentTime.ToString(@"mm\:ss");
var hrs = (int)CurrentTime.TotalHours;
if (hrs > 0)
return hrs + ":" + time;
else
return time;
}
}
private string PrettyTotalTime { private string PrettyTotalTime {
get { get {

View File

@ -37,7 +37,7 @@ namespace NadekoBot.Modules.Music
Directory.CreateDirectory(MusicDataPath); Directory.CreateDirectory(MusicDataPath);
} }
private static async void Client_UserVoiceStateUpdated(SocketUser iusr, SocketVoiceState oldState, SocketVoiceState newState) private static async Task Client_UserVoiceStateUpdated(SocketUser iusr, SocketVoiceState oldState, SocketVoiceState newState)
{ {
var usr = iusr as SocketGuildUser; var usr = iusr as SocketGuildUser;
if (usr == null || if (usr == null ||
@ -47,18 +47,36 @@ namespace NadekoBot.Modules.Music
MusicPlayer player; MusicPlayer player;
if (!MusicPlayers.TryGetValue(usr.Guild.Id, out player)) if (!MusicPlayers.TryGetValue(usr.Guild.Id, out player))
return; return;
try try
{ {
var users = await player.PlaybackVoiceChannel.GetUsersAsync().Flatten().ConfigureAwait(false);
//if bot moved
if ((player.PlaybackVoiceChannel == oldState.VoiceChannel) &&
usr.Id == NadekoBot.Client.CurrentUser.Id)
{
if (player.Paused && newState.VoiceChannel.Users.Count > 1) //unpause if there are people in the new channel
player.TogglePause();
else if (!player.Paused && newState.VoiceChannel.Users.Count <= 1) // pause if there are no users in the new channel
player.TogglePause();
return;
}
//if some other user moved
if ((player.PlaybackVoiceChannel == newState.VoiceChannel && //if joined first, and player paused, unpause if ((player.PlaybackVoiceChannel == newState.VoiceChannel && //if joined first, and player paused, unpause
player.Paused && player.Paused &&
users.Count() == 2) || // keep in mind bot is in the channel (+1) newState.VoiceChannel.Users.Count == 2) || // keep in mind bot is in the channel (+1)
(player.PlaybackVoiceChannel == oldState.VoiceChannel && // if left last, and player unpaused, pause (player.PlaybackVoiceChannel == oldState.VoiceChannel && // if left last, and player unpaused, pause
!player.Paused && !player.Paused &&
users.Count() == 1)) oldState.VoiceChannel.Users.Count == 1))
{ {
player.TogglePause(); player.TogglePause();
return;
} }
} }
catch { } catch { }
} }
@ -192,7 +210,7 @@ namespace NadekoBot.Modules.Music
int startAt = itemsPerPage * (curPage - 1); int startAt = itemsPerPage * (curPage - 1);
var number = 0 + startAt; var number = 0 + startAt;
var embed = new EmbedBuilder() var embed = new EmbedBuilder()
.WithAuthor(eab => eab.WithName($"Player Queue") .WithAuthor(eab => eab.WithName($"Player Queue - Page {curPage}/{lastPage + 1}")
.WithMusicIcon()) .WithMusicIcon())
.WithDescription(string.Join("\n", musicPlayer.Playlist .WithDescription(string.Join("\n", musicPlayer.Playlist
.Skip(startAt) .Skip(startAt)
@ -217,7 +235,7 @@ namespace NadekoBot.Modules.Music
} }
return embed; return embed;
}; };
await Context.Channel.SendPaginatedConfirmAsync(page, printAction, lastPage).ConfigureAwait(false); await Context.Channel.SendPaginatedConfirmAsync(page, printAction, lastPage, false).ConfigureAwait(false);
} }
[NadekoCommand, Usage, Description, Aliases] [NadekoCommand, Usage, Description, Aliases]
@ -448,17 +466,17 @@ namespace NadekoBot.Modules.Music
} }
[NadekoCommand, Usage, Description, Aliases] //[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)] //[RequireContext(ContextType.Guild)]
public async Task Move() //public async Task Move()
{ //{
MusicPlayer musicPlayer; // MusicPlayer musicPlayer;
var voiceChannel = ((IGuildUser)Context.User).VoiceChannel; // var voiceChannel = ((IGuildUser)Context.User).VoiceChannel;
if (voiceChannel == null || voiceChannel.Guild != Context.Guild || !MusicPlayers.TryGetValue(Context.Guild.Id, out musicPlayer)) // if (voiceChannel == null || voiceChannel.Guild != Context.Guild || !MusicPlayers.TryGetValue(Context.Guild.Id, out musicPlayer))
return; // return;
await musicPlayer.MoveToVoiceChannel(voiceChannel); // await musicPlayer.MoveToVoiceChannel(voiceChannel);
} //}
[NadekoCommand, Usage, Description, Aliases] [NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)] [RequireContext(ContextType.Guild)]
@ -814,7 +832,7 @@ namespace NadekoBot.Modules.Music
.WithFooter(ef => ef.WithText(song.PrettyInfo))) .WithFooter(ef => ef.WithText(song.PrettyInfo)))
.ConfigureAwait(false); .ConfigureAwait(false);
if (mp.Autoplay && mp.Playlist.Count == 0 && song.SongInfo.Provider == "YouTube") if (mp.Autoplay && mp.Playlist.Count == 0 && song.SongInfo.ProviderType == MusicType.Normal)
{ {
await QueueSong(await queuer.Guild.GetCurrentUserAsync(), textCh, voiceCh, (await NadekoBot.Google.GetRelatedVideosAsync(song.SongInfo.Query, 4)).ToList().Shuffle().FirstOrDefault(), silent, musicType).ConfigureAwait(false); await QueueSong(await queuer.Guild.GetCurrentUserAsync(), textCh, voiceCh, (await NadekoBot.Google.GetRelatedVideosAsync(song.SongInfo.Query, 4)).ToList().Shuffle().FirstOrDefault(), silent, musicType).ConfigureAwait(false);
} }

View File

@ -20,6 +20,7 @@ namespace NadekoBot.Modules.NSFW
public class NSFW : DiscordModule public class NSFW : DiscordModule
{ {
private static ConcurrentDictionary<ulong, Timer> AutoHentaiTimers { get; } = new ConcurrentDictionary<ulong, Timer>(); private static ConcurrentDictionary<ulong, Timer> AutoHentaiTimers { get; } = new ConcurrentDictionary<ulong, Timer>();
private static ConcurrentHashSet<ulong> _hentaiBombBlacklist { get; } = new ConcurrentHashSet<ulong>();
private async Task InternalHentai(IMessageChannel channel, string tag, bool noError) private async Task InternalHentai(IMessageChannel channel, string tag, bool noError)
{ {
@ -56,7 +57,8 @@ namespace NadekoBot.Modules.NSFW
await channel.EmbedAsync(new EmbedBuilder().WithOkColor() await channel.EmbedAsync(new EmbedBuilder().WithOkColor()
.WithImageUrl(link) .WithImageUrl(link)
.WithDescription("Tag: " + tag)).ConfigureAwait(false); .WithDescription("Tag: " + tag))
.ConfigureAwait(false);
} }
[NadekoCommand, Usage, Description, Aliases] [NadekoCommand, Usage, Description, Aliases]
@ -90,7 +92,7 @@ namespace NadekoBot.Modules.NSFW
if (tagsArr == null || tagsArr.Length == 0) if (tagsArr == null || tagsArr.Length == 0)
await InternalHentai(Context.Channel, null, true).ConfigureAwait(false); await InternalHentai(Context.Channel, null, true).ConfigureAwait(false);
else else
await InternalHentai(Context.Channel, tagsArr[new NadekoRandom().Next(0, tagsArr.Length)], true); await InternalHentai(Context.Channel, tagsArr[new NadekoRandom().Next(0, tagsArr.Length)], true).ConfigureAwait(false);
} }
catch { } catch { }
}, null, interval * 1000, interval * 1000); }, null, interval * 1000, interval * 1000);
@ -101,29 +103,39 @@ namespace NadekoBot.Modules.NSFW
return t; return t;
}); });
await Context.Channel.SendConfirmAsync($"Autohentai started. Reposting every {interval}s with one of the following tags:\n{string.Join(", ", tagsArr)}").ConfigureAwait(false); await Context.Channel.SendConfirmAsync($"Autohentai started. Reposting every {interval}s with one of the following tags:\n{string.Join(", ", tagsArr)}")
.ConfigureAwait(false);
} }
[NadekoCommand, Usage, Description, Aliases] [NadekoCommand, Usage, Description, Aliases]
public async Task HentaiBomb([Remainder] string tag = null) public async Task HentaiBomb([Remainder] string tag = null)
{ {
tag = tag?.Trim() ?? ""; if (!_hentaiBombBlacklist.Add(Context.User.Id))
tag = "rating%3Aexplicit+" + tag;
var links = await Task.WhenAll(GetGelbooruImageLink(tag),
GetDanbooruImageLink(tag),
GetKonachanImageLink(tag),
GetYandereImageLink(tag)).ConfigureAwait(false);
var linksEnum = links?.Where(l => l != null);
if (links == null || !linksEnum.Any())
{
await Context.Channel.SendErrorAsync("No results found.").ConfigureAwait(false);
return; return;
} try
{
tag = tag?.Trim() ?? "";
tag = "rating%3Aexplicit+" + tag;
await Context.Channel.SendMessageAsync(String.Join("\n\n", linksEnum)).ConfigureAwait(false); var links = await Task.WhenAll(GetGelbooruImageLink(tag),
GetDanbooruImageLink(tag),
GetKonachanImageLink(tag),
GetYandereImageLink(tag)).ConfigureAwait(false);
var linksEnum = links?.Where(l => l != null);
if (links == null || !linksEnum.Any())
{
await Context.Channel.SendErrorAsync("No results found.").ConfigureAwait(false);
return;
}
await Context.Channel.SendMessageAsync(String.Join("\n\n", linksEnum)).ConfigureAwait(false);
}
finally {
await Task.Delay(5000).ConfigureAwait(false);
_hentaiBombBlacklist.TryRemove(Context.User.Id);
}
} }
@ -135,12 +147,13 @@ namespace NadekoBot.Modules.NSFW
var url = await GetDanbooruImageLink(tag).ConfigureAwait(false); var url = await GetDanbooruImageLink(tag).ConfigureAwait(false);
if (url == null) if (url == null)
await Context.Channel.SendErrorAsync(Context.User.Mention + " No results."); await Context.Channel.SendErrorAsync(Context.User.Mention + " No results.").ConfigureAwait(false);
else else
await Context.Channel.EmbedAsync(new EmbedBuilder().WithOkColor() await Context.Channel.EmbedAsync(new EmbedBuilder().WithOkColor()
.WithDescription(Context.User.Mention + " " + tag) .WithDescription(Context.User.Mention + " " + tag)
.WithImageUrl(url) .WithImageUrl(url)
.WithFooter(efb => efb.WithText("Danbooru"))).ConfigureAwait(false); .WithFooter(efb => efb.WithText("Danbooru")))
.ConfigureAwait(false);
} }
[NadekoCommand, Usage, Description, Aliases] [NadekoCommand, Usage, Description, Aliases]
@ -172,7 +185,8 @@ namespace NadekoBot.Modules.NSFW
await Context.Channel.EmbedAsync(new EmbedBuilder().WithOkColor() await Context.Channel.EmbedAsync(new EmbedBuilder().WithOkColor()
.WithDescription(Context.User.Mention + " " + tag) .WithDescription(Context.User.Mention + " " + tag)
.WithImageUrl(url) .WithImageUrl(url)
.WithFooter(efb => efb.WithText("e621"))).ConfigureAwait(false); .WithFooter(efb => efb.WithText("e621")))
.ConfigureAwait(false);
} }
[NadekoCommand, Usage, Description, Aliases] [NadekoCommand, Usage, Description, Aliases]
@ -217,14 +231,14 @@ namespace NadekoBot.Modules.NSFW
} }
} }
public static async Task<string> GetDanbooruImageLink(string tag) public static Task<string> GetDanbooruImageLink(string tag) => Task.Run(async () =>
{ {
try try
{ {
using (var http = new HttpClient()) using (var http = new HttpClient())
{ {
http.AddFakeHeaders(); http.AddFakeHeaders();
var data = await http.GetStreamAsync("https://danbooru.donmai.us/posts.xml?limit=100&tags=" + tag); var data = await http.GetStreamAsync("https://danbooru.donmai.us/posts.xml?limit=100&tags=" + tag).ConfigureAwait(false);
var doc = new XmlDocument(); var doc = new XmlDocument();
doc.Load(data); doc.Load(data);
var nodes = doc.GetElementsByTagName("file-url"); var nodes = doc.GetElementsByTagName("file-url");
@ -237,17 +251,17 @@ namespace NadekoBot.Modules.NSFW
{ {
return null; return null;
} }
} });
public static async Task<string> GetE621ImageLink(string tag) public static Task<string> GetE621ImageLink(string tag) => Task.Run(async () =>
{ {
try try
{ {
using (var http = new HttpClient()) using (var http = new HttpClient())
{ {
http.AddFakeHeaders(); http.AddFakeHeaders();
var data = await http.GetStreamAsync("http://e621.net/post/index.xml?tags=" + tag); var data = await http.GetStreamAsync("http://e621.net/post/index.xml?tags=" + tag).ConfigureAwait(false);
var doc = new XmlDocument(); var doc = new XmlDocument();
doc.Load(data); doc.Load(data);
var nodes = doc.GetElementsByTagName("file_url"); var nodes = doc.GetElementsByTagName("file_url");
@ -260,7 +274,7 @@ namespace NadekoBot.Modules.NSFW
{ {
return null; return null;
} }
} });
public static Task<string> GetYandereImageLink(string tag) => public static Task<string> GetYandereImageLink(string tag) =>
Searches.Searches.InternalDapiSearch(tag, Searches.Searches.DapiSearchType.Yandere); Searches.Searches.InternalDapiSearch(tag, Searches.Searches.DapiSearchType.Yandere);

View File

@ -0,0 +1,101 @@
using Discord;
using Discord.Commands;
using NadekoBot.Attributes;
using NadekoBot.Extensions;
using NadekoBot.Services;
using NadekoBot.Services.Database;
using NadekoBot.Services.Database.Models;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NadekoBot.Modules.Permissions
{
public partial class Permissions
{
[Group]
public class CommandCostCommands : ModuleBase
{
private static readonly ConcurrentDictionary<string, int> _commandCosts = new ConcurrentDictionary<string, int>();
public static IReadOnlyDictionary<string, int> CommandCosts => _commandCosts;
static CommandCostCommands()
{
//_commandCosts = new ConcurrentDictionary<string, int>(NadekoBot.BotConfig.CommandCosts.ToDictionary(
// x => x.CommandName.Trim().ToUpperInvariant(),
// x => x.Cost));
}
[NadekoCommand, Usage, Description, Aliases]
public async Task CmdCosts(int page = 1)
{
var prices = _commandCosts.ToList();
if (!prices.Any())
{
await Context.Channel.SendConfirmAsync("No costs set.").ConfigureAwait(false);
return;
}
await Context.Channel.SendPaginatedConfirmAsync(page, (curPage) => {
var embed = new EmbedBuilder().WithOkColor()
.WithTitle("Command Costs");
var current = prices.Skip((curPage - 1) * 9)
.Take(9);
foreach (var price in current)
{
embed.AddField(efb => efb.WithName(price.Key).WithValue(price.Value.ToString()).WithIsInline(true));
}
return embed;
}, prices.Count / 9).ConfigureAwait(false);
}
//[NadekoCommand, Usage, Description, Aliases]
//public async Task CommandCost(int cost, CommandInfo cmd)
//{
// if (cost < 0)
// return;
// var cmdName = cmd.Aliases.First().ToLowerInvariant();
// var cmdPrice = new CommandCost()
// {
// CommandName = cmdName,
// Cost = cost
// };
// using (var uow = DbHandler.UnitOfWork())
// {
// var bc = uow.BotConfig.GetOrCreate();
// if (cost != 0)
// {
// var elem = bc.CommandCosts.Where(cc => cc.CommandName == cmdPrice.CommandName).FirstOrDefault();
// if (elem == null)
// bc.CommandCosts.Add(cmdPrice);
// else
// elem.Cost = cost;
// _commandCosts.AddOrUpdate(cmdName, cost, (key, old) => cost);
// }
// else
// {
// bc.CommandCosts.RemoveAt(bc.CommandCosts.IndexOf(cmdPrice));
// int throwaway;
// _commandCosts.TryRemove(cmdName, out throwaway);
// }
// await uow.CompleteAsync().ConfigureAwait(false);
// }
// if (cost == 0)
// await Context.Channel.SendConfirmAsync($"Removed the cost from the {Format.Bold(cmd.Name)} command.").ConfigureAwait(false);
// else
// await Context.Channel.SendConfirmAsync($"{Format.Bold(cmd.Name)} now costs {cost}{NadekoBot.BotConfig.CurrencySign} to run.").ConfigureAwait(false);
//}
}
}
}

View File

@ -517,7 +517,8 @@ namespace NadekoBot.Modules.Searches
.WithAuthor(eab => eab.WithUrl(link) .WithAuthor(eab => eab.WithUrl(link)
.WithIconUrl("http://res.cloudinary.com/urbandictionary/image/upload/a_exif,c_fit,h_200,w_200/v1394975045/b8oszuu3tbq7ebyo7vo1.jpg") .WithIconUrl("http://res.cloudinary.com/urbandictionary/image/upload/a_exif,c_fit,h_200,w_200/v1394975045/b8oszuu3tbq7ebyo7vo1.jpg")
.WithName(query)) .WithName(query))
.WithDescription(desc)); .WithDescription(desc))
.ConfigureAwait(false);
} }
catch catch
{ {
@ -572,9 +573,9 @@ namespace NadekoBot.Modules.Searches
var result = await http.GetStringAsync("https://en.wikipedia.org//w/api.php?action=query&format=json&prop=info&redirects=1&formatversion=2&inprop=url&titles=" + Uri.EscapeDataString(query)); var result = await http.GetStringAsync("https://en.wikipedia.org//w/api.php?action=query&format=json&prop=info&redirects=1&formatversion=2&inprop=url&titles=" + Uri.EscapeDataString(query));
var data = JsonConvert.DeserializeObject<WikipediaApiModel>(result); var data = JsonConvert.DeserializeObject<WikipediaApiModel>(result);
if (data.Query.Pages[0].Missing) if (data.Query.Pages[0].Missing)
await Context.Channel.SendErrorAsync("That page could not be found."); await Context.Channel.SendErrorAsync("That page could not be found.").ConfigureAwait(false);
else else
await Context.Channel.SendMessageAsync(data.Query.Pages[0].FullUrl); await Context.Channel.SendMessageAsync(data.Query.Pages[0].FullUrl).ConfigureAwait(false);
} }
} }
@ -588,7 +589,7 @@ namespace NadekoBot.Modules.Searches
img.BackgroundColor(new ImageSharp.Color(color)); img.BackgroundColor(new ImageSharp.Color(color));
await Context.Channel.SendFileAsync(img.ToStream(), $"{color}.png"); await Context.Channel.SendFileAsync(img.ToStream(), $"{color}.png").ConfigureAwait(false); ;
} }
[NadekoCommand, Usage, Description, Aliases] [NadekoCommand, Usage, Description, Aliases]
@ -642,7 +643,7 @@ namespace NadekoBot.Modules.Searches
var response = $@"`Title:` {found["title"].ToString()} var response = $@"`Title:` {found["title"].ToString()}
`Quality:` {found["quality"]} `Quality:` {found["quality"]}
`URL:` {await NadekoBot.Google.ShortenUrl(found["url"].ToString()).ConfigureAwait(false)}"; `URL:` {await NadekoBot.Google.ShortenUrl(found["url"].ToString()).ConfigureAwait(false)}";
await Context.Channel.SendMessageAsync(response); await Context.Channel.SendMessageAsync(response).ConfigureAwait(false);
} }
catch catch
{ {
@ -774,20 +775,24 @@ namespace NadekoBot.Modules.Searches
} }
try try
{ {
using (var http = new HttpClient()) var toReturn = await Task.Run(async () =>
{ {
http.AddFakeHeaders(); using (var http = new HttpClient())
var data = await http.GetStreamAsync(website); {
var doc = new XmlDocument(); http.AddFakeHeaders();
doc.Load(data); var data = await http.GetStreamAsync(website).ConfigureAwait(false);
var doc = new XmlDocument();
doc.Load(data);
var node = doc.LastChild.ChildNodes[new NadekoRandom().Next(0, doc.LastChild.ChildNodes.Count)]; var node = doc.LastChild.ChildNodes[new NadekoRandom().Next(0, doc.LastChild.ChildNodes.Count)];
var url = node.Attributes["file_url"].Value; var url = node.Attributes["file_url"].Value;
if (!url.StartsWith("http")) if (!url.StartsWith("http"))
url = "https:" + url; url = "https:" + url;
return url; return url;
} }
}).ConfigureAwait(false);
return toReturn;
} }
catch catch
{ {

View File

@ -31,7 +31,7 @@ namespace NadekoBot.Modules.Utility
var channel = imsg.Channel as ITextChannel; var channel = imsg.Channel as ITextChannel;
if (channel == null) if (channel == null)
return; return;
if (msg.Author.Id == NadekoBot.Client.CurrentUser().Id) return; if (msg.Author.Id == NadekoBot.Client.CurrentUser.Id) return;
foreach (var subscriber in Subscribers) foreach (var subscriber in Subscribers)
{ {
var set = subscriber.Value; var set = subscriber.Value;

View File

@ -277,27 +277,25 @@ namespace NadekoBot.Modules.Utility
.WithIconUrl("https://cdn.discordapp.com/avatars/116275390695079945/b21045e778ef21c96d175400e779f0fb.jpg")) .WithIconUrl("https://cdn.discordapp.com/avatars/116275390695079945/b21045e778ef21c96d175400e779f0fb.jpg"))
.AddField(efb => efb.WithName(Format.Bold("Author")).WithValue(stats.Author).WithIsInline(true)) .AddField(efb => efb.WithName(Format.Bold("Author")).WithValue(stats.Author).WithIsInline(true))
.AddField(efb => efb.WithName(Format.Bold("Library")).WithValue(stats.Library).WithIsInline(true)) .AddField(efb => efb.WithName(Format.Bold("Library")).WithValue(stats.Library).WithIsInline(true))
.AddField(efb => efb.WithName(Format.Bold("Bot ID")).WithValue(NadekoBot.Client.CurrentUser().Id.ToString()).WithIsInline(true)) .AddField(efb => efb.WithName(Format.Bold("Bot ID")).WithValue(NadekoBot.Client.CurrentUser.Id.ToString()).WithIsInline(true))
.AddField(efb => efb.WithName(Format.Bold("Commands Ran")).WithValue(stats.CommandsRan.ToString()).WithIsInline(true)) .AddField(efb => efb.WithName(Format.Bold("Commands Ran")).WithValue(stats.CommandsRan.ToString()).WithIsInline(true))
.AddField(efb => efb.WithName(Format.Bold("Messages")).WithValue($"{stats.MessageCounter} ({stats.MessagesPerSecond:F2}/sec)").WithIsInline(true)) .AddField(efb => efb.WithName(Format.Bold("Messages")).WithValue($"{stats.MessageCounter} ({stats.MessagesPerSecond:F2}/sec)").WithIsInline(true))
.AddField(efb => efb.WithName(Format.Bold("Memory")).WithValue($"{stats.Heap} MB").WithIsInline(true)) .AddField(efb => efb.WithName(Format.Bold("Memory")).WithValue($"{stats.Heap} MB").WithIsInline(true))
.AddField(efb => efb.WithName(Format.Bold("Owner ID(s)")).WithValue(string.Join("\n", NadekoBot.Credentials.OwnerIds)).WithIsInline(true)) .AddField(efb => efb.WithName(Format.Bold("Owner ID(s)")).WithValue(string.Join("\n", NadekoBot.Credentials.OwnerIds)).WithIsInline(true))
.AddField(efb => efb.WithName(Format.Bold("Uptime")).WithValue(stats.GetUptimeString("\n")).WithIsInline(true)) .AddField(efb => efb.WithName(Format.Bold("Uptime")).WithValue(stats.GetUptimeString("\n")).WithIsInline(true))
.AddField(efb => efb.WithName(Format.Bold("Presence")).WithValue($"{NadekoBot.Client.GetGuildsCount()} Servers\n{stats.TextChannels} Text Channels\n{stats.VoiceChannels} Voice Channels").WithIsInline(true)) .AddField(efb => efb.WithName(Format.Bold("Presence")).WithValue($"{NadekoBot.Client.GetGuildCount()} Servers\n{stats.TextChannels} Text Channels\n{stats.VoiceChannels} Voice Channels").WithIsInline(true))
#if !GLOBAL_NADEKO #if !GLOBAL_NADEKO
.WithFooter(efb => efb.WithText($"Playing {Music.Music.MusicPlayers.Where(mp => mp.Value.CurrentSong != null).Count()} songs, {Music.Music.MusicPlayers.Sum(mp => mp.Value.Playlist.Count)} queued.")) .WithFooter(efb => efb.WithText($"Playing {Music.Music.MusicPlayers.Where(mp => mp.Value.CurrentSong != null).Count()} songs, {Music.Music.MusicPlayers.Sum(mp => mp.Value.Playlist.Count)} queued."))
#endif #endif
); );
} }
private Regex emojiFinder { get; } = new Regex(@"<:(?<name>.+?):(?<id>\d*)>", RegexOptions.Compiled);
[NadekoCommand, Usage, Description, Aliases] [NadekoCommand, Usage, Description, Aliases]
public async Task Showemojis([Remainder] string emojis) public async Task Showemojis([Remainder] string emojis)
{ {
var matches = emojiFinder.Matches(emojis); var tags = Context.Message.Tags.Where(t => t.Type == TagType.Emoji).Select(t => (Emoji)t.Value);
var result = string.Join("\n", matches.Cast<Match>() var result = string.Join("\n", tags.Select(m => $"**Name:** {m} **Link:** {m.Url}"));
.Select(m => $"**Name:** {m.Groups["name"]} **Link:** http://discordapp.com/api/emojis/{m.Groups["id"]}.png"));
if (string.IsNullOrWhiteSpace(result)) if (string.IsNullOrWhiteSpace(result))
await Context.Channel.SendErrorAsync("No special emojis found."); await Context.Channel.SendErrorAsync("No special emojis found.");

View File

@ -28,7 +28,7 @@ namespace NadekoBot
public static CommandService CommandService { get; private set; } public static CommandService CommandService { get; private set; }
public static CommandHandler CommandHandler { get; private set; } public static CommandHandler CommandHandler { get; private set; }
public static ShardedDiscordClient Client { get; private set; } public static DiscordShardedClient Client { get; private set; }
public static BotCredentials Credentials { get; private set; } public static BotCredentials Credentials { get; private set; }
public static GoogleApiService Google { get; private set; } public static GoogleApiService Google { get; private set; }
@ -59,7 +59,7 @@ namespace NadekoBot
_log.Info("Starting NadekoBot v" + StatsService.BotVersion); _log.Info("Starting NadekoBot v" + StatsService.BotVersion);
//create client //create client
Client = new ShardedDiscordClient(new DiscordSocketConfig Client = new DiscordShardedClient(new DiscordSocketConfig
{ {
AudioMode = Discord.Audio.AudioMode.Outgoing, AudioMode = Discord.Audio.AudioMode.Outgoing,
MessageCacheSize = 10, MessageCacheSize = 10,
@ -68,6 +68,8 @@ namespace NadekoBot
ConnectionTimeout = int.MaxValue ConnectionTimeout = int.MaxValue
}); });
Client.Log += Client_Log;
//initialize Services //initialize Services
CommandService = new CommandService(new CommandServiceConfig() { CommandService = new CommandService(new CommandServiceConfig() {
CaseSensitiveCommands = false CaseSensitiveCommands = false
@ -93,6 +95,7 @@ namespace NadekoBot
//connect //connect
await Client.LoginAsync(TokenType.Bot, Credentials.Token).ConfigureAwait(false); await Client.LoginAsync(TokenType.Bot, Credentials.Token).ConfigureAwait(false);
await Client.ConnectAsync().ConfigureAwait(false); await Client.ConnectAsync().ConfigureAwait(false);
Stats.Initialize();
#if !GLOBAL_NADEKO #if !GLOBAL_NADEKO
await Client.DownloadAllUsersAsync().ConfigureAwait(false); await Client.DownloadAllUsersAsync().ConfigureAwait(false);
#endif #endif
@ -114,6 +117,15 @@ namespace NadekoBot
Console.WriteLine(await Stats.Print().ConfigureAwait(false)); Console.WriteLine(await Stats.Print().ConfigureAwait(false));
} }
private Task Client_Log(LogMessage arg)
{
_log.Warn(arg.Source + " | " + arg.Message);
if (arg.Exception != null)
_log.Warn(arg.Exception);
return Task.CompletedTask;
}
public async Task RunAndBlockAsync(params string[] args) public async Task RunAndBlockAsync(params string[] args)
{ {
await RunAsync(args).ConfigureAwait(false); await RunAsync(args).ConfigureAwait(false);

View File

@ -1760,6 +1760,33 @@ namespace NadekoBot.Resources {
} }
} }
/// <summary>
/// Looks up a localized string similar to cmdcosts.
/// </summary>
public static string cmdcosts_cmd {
get {
return ResourceManager.GetString("cmdcosts_cmd", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Shows a list of command costs. Paginated with 9 command per page..
/// </summary>
public static string cmdcosts_desc {
get {
return ResourceManager.GetString("cmdcosts_desc", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to `{0}cmdcosts` or `{0}cmdcosts 2`.
/// </summary>
public static string cmdcosts_usage {
get {
return ResourceManager.GetString("cmdcosts_usage", resourceCulture);
}
}
/// <summary> /// <summary>
/// Looks up a localized string similar to color clr. /// Looks up a localized string similar to color clr.
/// </summary> /// </summary>
@ -1787,6 +1814,33 @@ namespace NadekoBot.Resources {
} }
} }
/// <summary>
/// Looks up a localized string similar to commandcost cmdcost.
/// </summary>
public static string commandcost_cmd {
get {
return ResourceManager.GetString("commandcost_cmd", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Sets a price for a command. Running that command will take currency from users. Set 0 to remove the price..
/// </summary>
public static string commandcost_desc {
get {
return ResourceManager.GetString("commandcost_desc", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to `{0}cmdcost 0 !!q` or `{0}cmdcost 1 &gt;8ball`.
/// </summary>
public static string commandcost_usage {
get {
return ResourceManager.GetString("commandcost_usage", resourceCulture);
}
}
/// <summary> /// <summary>
/// Looks up a localized string similar to commands cmds. /// Looks up a localized string similar to commands cmds.
/// </summary> /// </summary>
@ -7241,6 +7295,33 @@ namespace NadekoBot.Resources {
} }
} }
/// <summary>
/// Looks up a localized string similar to startevent.
/// </summary>
public static string startevent_cmd {
get {
return ResourceManager.GetString("startevent_cmd", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Starts one of the events seen on public nadeko..
/// </summary>
public static string startevent_desc {
get {
return ResourceManager.GetString("startevent_desc", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to `{0}startevent flowerreaction`.
/// </summary>
public static string startevent_usage {
get {
return ResourceManager.GetString("startevent_usage", resourceCulture);
}
}
/// <summary> /// <summary>
/// Looks up a localized string similar to startwar sw. /// Looks up a localized string similar to startwar sw.
/// </summary> /// </summary>

View File

@ -2925,4 +2925,31 @@
<data name="antispamignore_usage" xml:space="preserve"> <data name="antispamignore_usage" xml:space="preserve">
<value>`{0}antispamignore`</value> <value>`{0}antispamignore`</value>
</data> </data>
<data name="cmdcosts_cmd" xml:space="preserve">
<value>cmdcosts</value>
</data>
<data name="cmdcosts_desc" xml:space="preserve">
<value>Shows a list of command costs. Paginated with 9 command per page.</value>
</data>
<data name="cmdcosts_usage" xml:space="preserve">
<value>`{0}cmdcosts` or `{0}cmdcosts 2`</value>
</data>
<data name="commandcost_cmd" xml:space="preserve">
<value>commandcost cmdcost</value>
</data>
<data name="commandcost_desc" xml:space="preserve">
<value>Sets a price for a command. Running that command will take currency from users. Set 0 to remove the price.</value>
</data>
<data name="commandcost_usage" xml:space="preserve">
<value>`{0}cmdcost 0 !!q` or `{0}cmdcost 1 &gt;8ball`</value>
</data>
<data name="startevent_cmd" xml:space="preserve">
<value>startevent</value>
</data>
<data name="startevent_desc" xml:space="preserve">
<value>Starts one of the events seen on public nadeko.</value>
</data>
<data name="startevent_usage" xml:space="preserve">
<value>`{0}startevent flowerreaction`</value>
</data>
</root> </root>

View File

@ -32,9 +32,9 @@ namespace NadekoBot.Services
{ {
public const int GlobalCommandsCooldown = 1500; public const int GlobalCommandsCooldown = 1500;
private ShardedDiscordClient _client; private readonly DiscordShardedClient _client;
private CommandService _commandService; private readonly CommandService _commandService;
private Logger _log; private readonly Logger _log;
private List<IDMChannel> ownerChannels { get; set; } private List<IDMChannel> ownerChannels { get; set; }
@ -46,7 +46,7 @@ namespace NadekoBot.Services
public ConcurrentHashSet<ulong> UsersOnShortCooldown { get; } = new ConcurrentHashSet<ulong>(); public ConcurrentHashSet<ulong> UsersOnShortCooldown { get; } = new ConcurrentHashSet<ulong>();
private Timer clearUsersOnShortCooldown { get; } private Timer clearUsersOnShortCooldown { get; }
public CommandHandler(ShardedDiscordClient client, CommandService commandService) public CommandHandler(DiscordShardedClient client, CommandService commandService)
{ {
_client = client; _client = client;
_commandService = commandService; _commandService = commandService;
@ -100,8 +100,8 @@ namespace NadekoBot.Services
BlacklistCommands.BlacklistedChannels.Contains(usrMsg.Channel.Id) || BlacklistCommands.BlacklistedChannels.Contains(usrMsg.Channel.Id) ||
BlacklistCommands.BlacklistedUsers.Contains(usrMsg.Author.Id); BlacklistCommands.BlacklistedUsers.Contains(usrMsg.Author.Id);
const float oneThousandth = 1.0f / 1000;
private async Task LogSuccessfulExecution(SocketUserMessage usrMsg, ExecuteCommandResult exec, SocketTextChannel channel, Stopwatch sw) private async Task LogSuccessfulExecution(SocketUserMessage usrMsg, ExecuteCommandResult exec, SocketTextChannel channel, int ticks)
{ {
await CommandExecuted(usrMsg, exec.CommandInfo).ConfigureAwait(false); await CommandExecuted(usrMsg, exec.CommandInfo).ConfigureAwait(false);
_log.Info("Command Executed after {4}s\n\t" + _log.Info("Command Executed after {4}s\n\t" +
@ -113,10 +113,10 @@ namespace NadekoBot.Services
(channel == null ? "PRIVATE" : channel.Guild.Name + " [" + channel.Guild.Id + "]"), // {1} (channel == null ? "PRIVATE" : channel.Guild.Name + " [" + channel.Guild.Id + "]"), // {1}
(channel == null ? "PRIVATE" : channel.Name + " [" + channel.Id + "]"), // {2} (channel == null ? "PRIVATE" : channel.Name + " [" + channel.Id + "]"), // {2}
usrMsg.Content, // {3} usrMsg.Content, // {3}
sw.Elapsed.TotalSeconds); ticks * oneThousandth);
} }
private void LogErroredExecution(SocketUserMessage usrMsg, ExecuteCommandResult exec, SocketTextChannel channel, Stopwatch sw) private void LogErroredExecution(SocketUserMessage usrMsg, ExecuteCommandResult exec, SocketTextChannel channel, int ticks)
{ {
_log.Warn("Command Errored after {5}s\n\t" + _log.Warn("Command Errored after {5}s\n\t" +
"User: {0}\n\t" + "User: {0}\n\t" +
@ -129,7 +129,7 @@ namespace NadekoBot.Services
(channel == null ? "PRIVATE" : channel.Name + " [" + channel.Id + "]"), // {2} (channel == null ? "PRIVATE" : channel.Name + " [" + channel.Id + "]"), // {2}
usrMsg.Content,// {3} usrMsg.Content,// {3}
exec.Result.ErrorReason, // {4} exec.Result.ErrorReason, // {4}
sw.Elapsed.TotalSeconds // {5} ticks * oneThousandth // {5}
); );
} }
@ -180,13 +180,15 @@ namespace NadekoBot.Services
return false; return false;
} }
private async void MessageReceivedHandler(SocketMessage msg) private async Task MessageReceivedHandler(SocketMessage msg)
{ {
try try
{ {
if (msg.Author.IsBot || !NadekoBot.Ready) //no bots, wait until bot connected and initialized if (msg.Author.IsBot || !NadekoBot.Ready) //no bots, wait until bot connected and initialized
return; return;
var execTime = Environment.TickCount;
var usrMsg = msg as SocketUserMessage; var usrMsg = msg as SocketUserMessage;
if (usrMsg == null) //has to be an user message, not system/other messages. if (usrMsg == null) //has to be an user message, not system/other messages.
return; return;
@ -226,17 +228,16 @@ namespace NadekoBot.Services
string messageContent = usrMsg.Content; string messageContent = usrMsg.Content;
// execute the command and measure the time it took // execute the command and measure the time it took
var sw = Stopwatch.StartNew(); var exec = await ExecuteCommand(new CommandContext(_client, usrMsg), messageContent, DependencyMap.Empty, MultiMatchHandling.Best);
var exec = await ExecuteCommand(new CommandContext(_client.MainClient, usrMsg), messageContent, DependencyMap.Empty, MultiMatchHandling.Best); execTime = Environment.TickCount - execTime;
sw.Stop();
if (exec.Result.IsSuccess) if (exec.Result.IsSuccess)
{ {
await LogSuccessfulExecution(usrMsg, exec, channel, sw).ConfigureAwait(false); await LogSuccessfulExecution(usrMsg, exec, channel, execTime).ConfigureAwait(false);
} }
else if (!exec.Result.IsSuccess && exec.Result.Error != CommandError.UnknownCommand) else if (!exec.Result.IsSuccess && exec.Result.Error != CommandError.UnknownCommand)
{ {
LogErroredExecution(usrMsg, exec, channel, sw); LogErroredExecution(usrMsg, exec, channel, execTime);
if (guild != null && exec.CommandInfo != null && exec.Result.Error == CommandError.Exception) if (guild != null && exec.CommandInfo != null && exec.Result.Error == CommandError.Exception)
{ {
if (exec.PermissionCache != null && exec.PermissionCache.Verbose) if (exec.PermissionCache != null && exec.PermissionCache.Verbose)
@ -348,11 +349,22 @@ namespace NadekoBot.Services
if (module.Name == typeof(Permissions).Name) if (module.Name == typeof(Permissions).Name)
{ {
if (!((IGuildUser)context.User).GetRoles().Any(r => r.Name.Trim().ToLowerInvariant() == pc.PermRole.Trim().ToLowerInvariant())) var guildUser = (IGuildUser)context.User;
if (!guildUser.GetRoles().Any(r => r.Name.Trim().ToLowerInvariant() == pc.PermRole.Trim().ToLowerInvariant()) && guildUser.Id != guildUser.Guild.OwnerId)
{ {
return new ExecuteCommandResult(cmd, pc, SearchResult.FromError(CommandError.Exception, $"You need the **{pc.PermRole}** role in order to use permission commands.")); return new ExecuteCommandResult(cmd, pc, SearchResult.FromError(CommandError.Exception, $"You need the **{pc.PermRole}** role in order to use permission commands."));
} }
} }
int price;
if (Permissions.CommandCostCommands.CommandCosts.TryGetValue(cmd.Aliases.First().Trim().ToLowerInvariant(), out price) && price > 0)
{
var success = await CurrencyHandler.RemoveCurrencyAsync(context.User.Id, $"Running {cmd.Name} command.", price).ConfigureAwait(false);
if (!success)
{
return new ExecuteCommandResult(cmd, pc, SearchResult.FromError(CommandError.Exception, $"Insufficient funds. You need {price}{NadekoBot.BotConfig.CurrencySign} to run this command."));
}
}
} }

View File

@ -19,11 +19,26 @@ namespace NadekoBot.Services.Database.Models
public bool RotatingStatuses { get; set; } = false; public bool RotatingStatuses { get; set; } = false;
public string RemindMessageFormat { get; set; } = "❗⏰**I've been told to remind you to '%message%' now by %user%.**⏰❗"; public string RemindMessageFormat { get; set; } = "❗⏰**I've been told to remind you to '%message%' now by %user%.**⏰❗";
//currency
public string CurrencySign { get; set; } = "🌸"; public string CurrencySign { get; set; } = "🌸";
public string CurrencyName { get; set; } = "Nadeko Flower"; public string CurrencyName { get; set; } = "Nadeko Flower";
public string CurrencyPluralName { get; set; } = "Nadeko Flowers"; public string CurrencyPluralName { get; set; } = "Nadeko Flowers";
public int TriviaCurrencyReward { get; set; } = 0;
public int MinimumBetAmount { get; set; } = 3;
public float BetflipMultiplier { get; set; } = 1.8f;
public int CurrencyDropAmount { get; set; } = 1;
public float Betroll67Multiplier { get; set; } = 2;
public float Betroll91Multiplier { get; set; } = 3;
public float Betroll100Multiplier { get; set; } = 10;
//public HashSet<CommandCost> CommandCosts { get; set; } = new HashSet<CommandCost>();
/// <summary>
/// I messed up, don't use
/// </summary>
public HashSet<CommandPrice> CommandPrices { get; set; } = new HashSet<CommandPrice>();
public HashSet<EightBallResponse> EightBallResponses { get; set; } = new HashSet<EightBallResponse>(); public HashSet<EightBallResponse> EightBallResponses { get; set; } = new HashSet<EightBallResponse>();
public HashSet<RaceAnimal> RaceAnimals { get; set; } = new HashSet<RaceAnimal>(); public HashSet<RaceAnimal> RaceAnimals { get; set; } = new HashSet<RaceAnimal>();

View File

@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NadekoBot.Services.Database.Models
{
public class CommandCost : DbEntity
{
public int Cost { get; set; }
public string CommandName { get; set; }
public override int GetHashCode() =>
CommandName.GetHashCode();
public override bool Equals(object obj)
{
var instance = obj as CommandCost;
if (instance == null)
return false;
return instance.CommandName == CommandName;
}
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NadekoBot.Services.Database.Models
{
public class CommandPrice : DbEntity
{
public int Price { get; set; }
//this is unique
public string CommandName { get; set; }
}
}

View File

@ -234,9 +234,15 @@ namespace NadekoBot.Services.Database
#endregion #endregion
#region Protection #region CommandPrice
//well, i failed
modelBuilder.Entity<CommandPrice>()
.HasIndex(cp => cp.Price)
.IsUnique();
//modelBuilder.Entity<CommandCost>()
// .HasIndex(cp => cp.CommandName)
// .IsUnique();
#endregion #endregion
} }
} }

View File

@ -17,6 +17,7 @@ namespace NadekoBot.Services.Database.Repositories.Impl
.Include(bc => bc.Blacklist) .Include(bc => bc.Blacklist)
.Include(bc => bc.EightBallResponses) .Include(bc => bc.EightBallResponses)
.Include(bc => bc.ModulePrefixes) .Include(bc => bc.ModulePrefixes)
//.Include(bc => bc.CommandCosts)
.FirstOrDefault(); .FirstOrDefault();
if (config == null) if (config == null)

View File

@ -26,7 +26,7 @@ namespace NadekoBot.Services.Discord
NadekoBot.Client.ReactionsCleared += Discord_ReactionsCleared; NadekoBot.Client.ReactionsCleared += Discord_ReactionsCleared;
} }
private void Discord_ReactionsCleared(ulong messageId, Optional<SocketUserMessage> reaction) private Task Discord_ReactionsCleared(ulong messageId, Optional<SocketUserMessage> reaction)
{ {
try try
{ {
@ -34,9 +34,11 @@ namespace NadekoBot.Services.Discord
OnReactionsCleared?.Invoke(); OnReactionsCleared?.Invoke();
} }
catch { } catch { }
return Task.CompletedTask;
} }
private void Discord_ReactionRemoved(ulong messageId, Optional<SocketUserMessage> arg2, SocketReaction reaction) private Task Discord_ReactionRemoved(ulong messageId, Optional<SocketUserMessage> arg2, SocketReaction reaction)
{ {
try try
{ {
@ -44,9 +46,11 @@ namespace NadekoBot.Services.Discord
OnReactionRemoved?.Invoke(reaction); OnReactionRemoved?.Invoke(reaction);
} }
catch { } catch { }
return Task.CompletedTask;
} }
private void Discord_ReactionAdded(ulong messageId, Optional<SocketUserMessage> message, SocketReaction reaction) private Task Discord_ReactionAdded(ulong messageId, Optional<SocketUserMessage> message, SocketReaction reaction)
{ {
try try
{ {
@ -54,6 +58,8 @@ namespace NadekoBot.Services.Discord
OnReactionAdded?.Invoke(reaction); OnReactionAdded?.Invoke(reaction);
} }
catch { } catch { }
return Task.CompletedTask;
} }
public void UnsubAll() public void UnsubAll()

View File

@ -51,7 +51,7 @@ namespace NadekoBot.Services.Impl
return (await query.ExecuteAsync()).Items.Select(i => i.Id.PlaylistId); return (await query.ExecuteAsync()).Items.Select(i => i.Id.PlaylistId);
} }
private readonly Regex YtVideoIdRegex = new Regex(@"(?:youtube\.com\/\S*(?:(?:\/e(?:mbed))?\/|watch\?(?:\S*?&?v\=))|youtu\.be\/)([a-zA-Z0-9_-]{6,11})", RegexOptions.Compiled); private readonly Regex YtVideoIdRegex = new Regex(@"(?:youtube\.com\/\S*(?:(?:\/e(?:mbed))?\/|watch\?(?:\S*?&?v\=))|youtu\.be\/)(?<id>[a-zA-Z0-9_-]{6,11})", RegexOptions.Compiled);
public async Task<IEnumerable<string>> GetRelatedVideosAsync(string id, int count = 1) public async Task<IEnumerable<string>> GetRelatedVideosAsync(string id, int count = 1)
{ {

View File

@ -1,4 +1,5 @@
using Discord; using Discord;
using Discord.WebSocket;
using NadekoBot.Extensions; using NadekoBot.Extensions;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@ -11,10 +12,10 @@ namespace NadekoBot.Services.Impl
{ {
public class StatsService : IStatsService public class StatsService : IStatsService
{ {
private ShardedDiscordClient client; private DiscordShardedClient client;
private DateTime started; private DateTime started;
public const string BotVersion = "1.1.0"; public const string BotVersion = "1.1.1";
public string Author => "Kwoth#2560"; public string Author => "Kwoth#2560";
public string Library => "Discord.Net"; public string Library => "Discord.Net";
@ -30,7 +31,7 @@ namespace NadekoBot.Services.Impl
Timer carbonitexTimer { get; } Timer carbonitexTimer { get; }
public StatsService(ShardedDiscordClient client, CommandHandler cmdHandler) public StatsService(DiscordShardedClient client, CommandHandler cmdHandler)
{ {
this.client = client; this.client = client;
@ -39,21 +40,14 @@ namespace NadekoBot.Services.Impl
this.client.MessageReceived += _ => Task.FromResult(MessageCounter++); this.client.MessageReceived += _ => Task.FromResult(MessageCounter++);
cmdHandler.CommandExecuted += (_, e) => Task.FromResult(CommandsRan++); cmdHandler.CommandExecuted += (_, e) => Task.FromResult(CommandsRan++);
this.client.Disconnected += _ => Reset();
this.client.Connected += () =>
{
var guilds = this.client.GetGuilds();
_textChannels = guilds.Sum(g => g.Channels.Where(cx => cx is ITextChannel).Count());
_voiceChannels = guilds.Sum(g => g.Channels.Count) - _textChannels;
};
this.client.ChannelCreated += (c) => this.client.ChannelCreated += (c) =>
{ {
if (c is ITextChannel) if (c is ITextChannel)
++_textChannels; ++_textChannels;
else if (c is IVoiceChannel) else if (c is IVoiceChannel)
++_voiceChannels; ++_voiceChannels;
return Task.CompletedTask;
}; };
this.client.ChannelDestroyed += (c) => this.client.ChannelDestroyed += (c) =>
@ -62,6 +56,8 @@ namespace NadekoBot.Services.Impl
--_textChannels; --_textChannels;
else if (c is IVoiceChannel) else if (c is IVoiceChannel)
--_voiceChannels; --_voiceChannels;
return Task.CompletedTask;
}; };
this.client.JoinedGuild += (g) => this.client.JoinedGuild += (g) =>
@ -70,6 +66,8 @@ namespace NadekoBot.Services.Impl
var vc = g.Channels.Count - tc; var vc = g.Channels.Count - tc;
_textChannels += tc; _textChannels += tc;
_voiceChannels += vc; _voiceChannels += vc;
return Task.CompletedTask;
}; };
this.client.LeftGuild += (g) => this.client.LeftGuild += (g) =>
@ -78,6 +76,8 @@ namespace NadekoBot.Services.Impl
var vc = g.Channels.Count - tc; var vc = g.Channels.Count - tc;
_textChannels -= tc; _textChannels -= tc;
_voiceChannels -= vc; _voiceChannels -= vc;
return Task.CompletedTask;
}; };
this.carbonitexTimer = new Timer(async (state) => this.carbonitexTimer = new Timer(async (state) =>
@ -90,7 +90,7 @@ namespace NadekoBot.Services.Impl
{ {
using (var content = new FormUrlEncodedContent( using (var content = new FormUrlEncodedContent(
new Dictionary<string, string> { new Dictionary<string, string> {
{ "servercount", this.client.GetGuildsCount().ToString() }, { "servercount", this.client.GetGuildCount().ToString() },
{ "key", NadekoBot.Credentials.CarbonKey }})) { "key", NadekoBot.Credentials.CarbonKey }}))
{ {
content.Headers.Clear(); content.Headers.Clear();
@ -103,16 +103,24 @@ namespace NadekoBot.Services.Impl
catch { } catch { }
}, null, TimeSpan.FromHours(1), TimeSpan.FromHours(1)); }, null, TimeSpan.FromHours(1), TimeSpan.FromHours(1));
} }
public void Initialize()
{
var guilds = this.client.GetGuilds();
_textChannels = guilds.Sum(g => g.Channels.Where(cx => cx is ITextChannel).Count());
_voiceChannels = guilds.Sum(g => g.Channels.Count) - _textChannels;
}
public Task<string> Print() public Task<string> Print()
{ {
var curUser = client.CurrentUser(); var curUser = client.CurrentUser;
return Task.FromResult($@" return Task.FromResult($@"
Author: [{Author}] | Library: [{Library}] Author: [{Author}] | Library: [{Library}]
Bot Version: [{BotVersion}] Bot Version: [{BotVersion}]
Bot ID: {curUser.Id} Bot ID: {curUser.Id}
Owner ID(s): {string.Join(", ", NadekoBot.Credentials.OwnerIds)} Owner ID(s): {string.Join(", ", NadekoBot.Credentials.OwnerIds)}
Uptime: {GetUptimeString()} Uptime: {GetUptimeString()}
Servers: {client.GetGuildsCount()} | TextChannels: {TextChannels} | VoiceChannels: {VoiceChannels} Servers: {client.GetGuildCount()} | TextChannels: {TextChannels} | VoiceChannels: {VoiceChannels}
Commands Ran this session: {CommandsRan} Commands Ran this session: {CommandsRan}
Messages: {MessageCounter} [{MessagesPerSecond:F2}/sec] Heap: [{Heap} MB]"); Messages: {MessageCounter} [{MessagesPerSecond:F2}/sec] Heap: [{Heap} MB]");
} }

View File

@ -60,7 +60,8 @@ namespace NadekoBot
client.MessageReceived += arg1 => client.MessageReceived += arg1 =>
{ {
if (arg1.Author == null || arg1.Author.IsBot) if (arg1.Author == null || arg1.Author.IsBot)
return Task.CompletedTask; MessageReceived(arg1); return Task.CompletedTask;
MessageReceived(arg1);
return Task.CompletedTask; return Task.CompletedTask;
}; };
client.UserLeft += arg1 => { UserLeft(arg1); return Task.CompletedTask; }; client.UserLeft += arg1 => { UserLeft(arg1); return Task.CompletedTask; };
@ -107,7 +108,7 @@ namespace NadekoBot
public DiscordSocketClient MainClient => public DiscordSocketClient MainClient =>
Clients[0]; Clients[0];
public SocketSelfUser CurrentUser() => public SocketSelfUser CurrentUser =>
Clients[0].CurrentUser; Clients[0].CurrentUser;
public IEnumerable<SocketGuild> GetGuilds() => public IEnumerable<SocketGuild> GetGuilds() =>
@ -178,26 +179,9 @@ namespace NadekoBot
public Task SetGame(string game) => Task.WhenAll(Clients.Select(ms => ms.SetGameAsync(game))); public Task SetGame(string game) => Task.WhenAll(Clients.Select(ms => ms.SetGameAsync(game)));
public Task SetStream(string name, string url) => Task.WhenAll(Clients.Select(ms => ms.SetGameAsync(name, url, StreamType.NotStreaming))); public Task SetStream(string name, string url) => Task.WhenAll(Clients.Select(ms => ms.SetGameAsync(name, url, StreamType.Twitch)));
public Task SetStatus(SettableUserStatus status) => Task.WhenAll(Clients.Select(ms => ms.SetStatusAsync(SettableUserStatusToUserStatus(status)))); //public Task SetStatus(SettableUserStatus status) => Task.WhenAll(Clients.Select(ms => ms.SetStatusAsync(SettableUserStatusToUserStatus(status))));
private static UserStatus SettableUserStatusToUserStatus(SettableUserStatus sus)
{
switch (sus)
{
case SettableUserStatus.Online:
return UserStatus.Online;
case SettableUserStatus.Invisible:
return UserStatus.Invisible;
case SettableUserStatus.Idle:
return UserStatus.AFK;
case SettableUserStatus.Dnd:
return UserStatus.DoNotDisturb;
}
return UserStatus.Online;
}
} }
public enum SettableUserStatus public enum SettableUserStatus

View File

@ -24,10 +24,13 @@ namespace NadekoBot.Extensions
/// <summary> /// <summary>
/// danny kamisama /// danny kamisama
/// </summary> /// </summary>
public static async Task SendPaginatedConfirmAsync(this IMessageChannel channel, int currentPage, Func<int, EmbedBuilder> pageFunc, int? lastPage = null) public static async Task SendPaginatedConfirmAsync(this IMessageChannel channel, int currentPage, Func<int, EmbedBuilder> pageFunc, int? lastPage = null, bool addPaginatedFooter = true)
{ {
lastPage += 1; lastPage += 1;
var embed = pageFunc(currentPage).AddPaginatedFooter(currentPage, lastPage); var embed = pageFunc(currentPage);
if(addPaginatedFooter)
embed.AddPaginatedFooter(currentPage, lastPage);
var msg = await channel.EmbedAsync(embed) as IUserMessage; var msg = await channel.EmbedAsync(embed) as IUserMessage;
@ -47,12 +50,20 @@ namespace NadekoBot.Extensions
{ {
if (currentPage == 1) if (currentPage == 1)
return; return;
await msg.ModifyAsync(x => x.Embed = pageFunc(--currentPage).AddPaginatedFooter(currentPage, lastPage).Build()).ConfigureAwait(false); var toSend = pageFunc(--currentPage);
if (addPaginatedFooter)
toSend.AddPaginatedFooter(currentPage, lastPage);
await msg.ModifyAsync(x => x.Embed = toSend.Build()).ConfigureAwait(false);
} }
else if (r.Emoji.Name == arrow_right) else if (r.Emoji.Name == arrow_right)
{ {
if (lastPage == null || lastPage > currentPage) if (lastPage == null || lastPage > currentPage)
await msg.ModifyAsync(x => x.Embed = pageFunc(++currentPage).AddPaginatedFooter(currentPage, lastPage).Build()).ConfigureAwait(false); {
var toSend = pageFunc(++currentPage);
if (addPaginatedFooter)
toSend.AddPaginatedFooter(currentPage, lastPage);
await msg.ModifyAsync(x => x.Embed = toSend.Build()).ConfigureAwait(false);
}
} }
} }
catch (Exception ex) { Console.WriteLine(ex); } catch (Exception ex) { Console.WriteLine(ex); }
@ -192,7 +203,7 @@ namespace NadekoBot.Extensions
await (await user.CreateDMChannelAsync().ConfigureAwait(false)).SendFileAsync(fileStream, fileName, caption, isTTS).ConfigureAwait(false); await (await user.CreateDMChannelAsync().ConfigureAwait(false)).SendFileAsync(fileStream, fileName, caption, isTTS).ConfigureAwait(false);
public static bool IsAuthor(this IUserMessage msg) => public static bool IsAuthor(this IUserMessage msg) =>
NadekoBot.Client.CurrentUser().Id == msg.Author.Id; NadekoBot.Client.CurrentUser.Id == msg.Author.Id;
public static IEnumerable<IUser> Members(this IRole role) => public static IEnumerable<IUser> Members(this IRole role) =>
role.Guild.GetUsersAsync().GetAwaiter().GetResult().Where(u => u.RoleIds.Contains(role.Id)) ?? Enumerable.Empty<IUser>(); role.Guild.GetUsersAsync().GetAwaiter().GetResult().Where(u => u.RoleIds.Contains(role.Id)) ?? Enumerable.Empty<IUser>();