2020-04-24 21:22:46 +00:00
using System ;
2020-06-24 14:47:34 +00:00
using System.Collections.Concurrent ;
2020-05-10 22:44:59 +00:00
using System.Collections.Generic ;
2020-06-28 18:26:14 +00:00
using System.Globalization ;
2020-05-10 22:44:59 +00:00
using System.Linq ;
using System.Reflection ;
2020-06-28 18:26:14 +00:00
using System.Text.RegularExpressions ;
2020-04-17 21:10:01 +00:00
using System.Threading.Tasks ;
using DSharpPlus ;
using DSharpPlus.Entities ;
2020-07-02 16:29:04 +00:00
using DSharpPlus.Exceptions ;
2020-04-17 21:10:01 +00:00
using NodaTime ;
2020-02-12 14:16:19 +00:00
2020-07-07 18:57:22 +00:00
using PluralKit.Core ;
2020-02-12 14:16:19 +00:00
namespace PluralKit.Bot
{
public static class DiscordUtils
{
2020-04-28 22:25:01 +00:00
public static DiscordColor Blue = new DiscordColor ( 0x1f99d8 ) ;
public static DiscordColor Green = new DiscordColor ( 0x00cc78 ) ;
public static DiscordColor Red = new DiscordColor ( 0xef4b3d ) ;
public static DiscordColor Gray = new DiscordColor ( 0x979c9f ) ;
2020-05-02 14:25:17 +00:00
public static Permissions DM_PERMISSIONS = ( Permissions ) 0 b00000_1000110_1011100110000_000000 ;
2020-07-02 16:29:04 +00:00
private static readonly Regex USER_MENTION = new Regex ( "<@!?(\\d{17,19})>" ) ;
private static readonly Regex ROLE_MENTION = new Regex ( "<@&(\\d{17,19})>" ) ;
private static readonly Regex EVERYONE_HERE_MENTION = new Regex ( "@(everyone|here)" ) ;
2020-07-10 14:35:52 +00:00
// Discord uses Khan Academy's simple-markdown library for parsing Markdown,
// which uses the following regex for link detection:
// ^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])
// Source: https://raw.githubusercontent.com/DJScias/Discord-Datamining/master/2020/2020-07-10/47efb8681861cb7c5ffa.js @ line 20633
// corresponding to: https://github.com/Khan/simple-markdown/blob/master/src/index.js#L1489
// I added <? and >? at the start/end; they need to be handled specially later...
private static readonly Regex UNBROKEN_LINK_REGEX = new Regex ( "<?(https?:\\/\\/[^\\s<]+[^<.,:;\"')\\]\\s])>?" ) ;
2020-05-10 22:44:59 +00:00
private static readonly FieldInfo _roleIdsField = typeof ( DiscordMember ) . GetField ( "_role_ids" , BindingFlags . NonPublic | BindingFlags . Instance ) ;
2020-04-17 21:10:01 +00:00
public static string NameAndMention ( this DiscordUser user ) {
2020-02-12 14:16:19 +00:00
return $"{user.Username}#{user.Discriminator} ({user.Mention})" ;
}
2020-04-17 21:10:01 +00:00
2020-05-02 14:25:17 +00:00
// We funnel all "permissions from DiscordMember" calls through here
// This way we can ensure we do the read permission correction everywhere
private static Permissions PermissionsInGuild ( DiscordChannel channel , DiscordMember member )
2020-02-12 14:16:19 +00:00
{
2020-05-10 22:44:59 +00:00
ValidateCachedRoles ( member ) ;
2020-05-02 14:25:17 +00:00
var permissions = channel . PermissionsFor ( member ) ;
2020-04-17 21:10:01 +00:00
2020-05-02 14:25:17 +00:00
// This method doesn't account for channels without read permissions
// If we don't have read permissions in the channel, we don't have *any* permissions
if ( ( permissions & Permissions . AccessChannels ) ! = Permissions . AccessChannels )
return Permissions . None ;
return permissions ;
2020-04-17 21:10:01 +00:00
}
2020-05-10 22:44:59 +00:00
// Workaround for DSP internal error
private static void ValidateCachedRoles ( DiscordMember member )
{
var roleIdCache = _roleIdsField . GetValue ( member ) as List < ulong > ;
var currentRoleIds = member . Roles . Where ( x = > x ! = null ) . Select ( x = > x . Id ) ;
2020-07-14 20:24:13 +00:00
var invalidRoleIds = roleIdCache . Where ( x = > ! currentRoleIds . Contains ( x ) ) . ToList ( ) ;
2020-05-10 22:44:59 +00:00
roleIdCache . RemoveAll ( x = > invalidRoleIds . Contains ( x ) ) ;
}
2020-05-02 14:25:17 +00:00
public static async Task < Permissions > PermissionsIn ( this DiscordChannel channel , DiscordUser user )
{
// Just delegates to PermissionsInSync, but handles the case of a non-member User in a guild properly
// This is a separate method because it requires an async call
if ( channel . Guild ! = null & & ! ( user is DiscordMember ) )
2020-07-02 16:29:04 +00:00
{
var member = await channel . Guild . GetMember ( user . Id ) ;
if ( member ! = null )
return PermissionsInSync ( channel , member ) ;
}
2020-05-02 14:25:17 +00:00
return PermissionsInSync ( channel , user ) ;
}
// Same as PermissionsIn, but always synchronous. DiscordUser must be a DiscordMember if channel is in guild.
2020-04-17 21:10:01 +00:00
public static Permissions PermissionsInSync ( this DiscordChannel channel , DiscordUser user )
{
2020-05-02 14:25:17 +00:00
if ( channel . Guild ! = null & & ! ( user is DiscordMember ) )
throw new ArgumentException ( "Function was passed a guild channel but a non-member DiscordUser" ) ;
2020-04-17 21:10:01 +00:00
2020-05-02 14:25:17 +00:00
if ( user is DiscordMember m ) return PermissionsInGuild ( channel , m ) ;
if ( channel . Type = = ChannelType . Private ) return DM_PERMISSIONS ;
2020-04-17 21:10:01 +00:00
return Permissions . None ;
2020-02-12 14:16:19 +00:00
}
2020-04-17 21:10:01 +00:00
public static Permissions BotPermissions ( this DiscordChannel channel )
{
2020-05-02 14:25:17 +00:00
// TODO: can we get a CurrentMember somehow without a guild context?
// at least, without somehow getting a DiscordClient reference as an arg(which I don't want to do)
2020-04-17 21:10:01 +00:00
if ( channel . Guild ! = null )
2020-05-02 14:25:17 +00:00
return PermissionsInSync ( channel , channel . Guild . CurrentMember ) ;
if ( channel . Type = = ChannelType . Private ) return DM_PERMISSIONS ;
2020-04-17 21:10:01 +00:00
return Permissions . None ;
}
2020-05-02 13:29:36 +00:00
public static bool BotHasAllPermissions ( this DiscordChannel channel , Permissions permissionSet ) = >
2020-04-17 21:10:01 +00:00
( BotPermissions ( channel ) & permissionSet ) = = permissionSet ;
public static Instant SnowflakeToInstant ( ulong snowflake ) = >
2020-04-24 21:22:46 +00:00
Instant . FromUtc ( 2015 , 1 , 1 , 0 , 0 , 0 ) + Duration . FromMilliseconds ( snowflake > > 22 ) ;
2020-04-17 21:10:01 +00:00
public static ulong InstantToSnowflake ( Instant time ) = >
2020-07-10 14:47:30 +00:00
( ulong ) ( time - Instant . FromUtc ( 2015 , 1 , 1 , 0 , 0 , 0 ) ) . TotalMilliseconds < < 22 ;
2020-04-17 21:10:01 +00:00
public static ulong InstantToSnowflake ( DateTimeOffset time ) = >
2020-07-10 14:47:30 +00:00
( ulong ) ( time - new DateTimeOffset ( 2015 , 1 , 1 , 0 , 0 , 0 , TimeSpan . Zero ) ) . TotalMilliseconds < < 22 ;
2020-04-17 21:10:01 +00:00
public static async Task CreateReactionsBulk ( this DiscordMessage msg , string [ ] reactions )
{
foreach ( var reaction in reactions )
{
await msg . CreateReactionAsync ( DiscordEmoji . FromUnicode ( reaction ) ) ;
}
}
2020-05-05 17:09:18 +00:00
public static string WorkaroundForUrlBug ( string input )
{
// Workaround for https://github.com/DSharpPlus/DSharpPlus/issues/565
2020-05-07 22:57:17 +00:00
return input ? . Replace ( "%20" , "+" ) ;
2020-05-05 17:09:18 +00:00
}
2020-06-20 15:33:10 +00:00
public static Task < DiscordMessage > SendMessageFixedAsync ( this DiscordChannel channel , string content = null , DiscordEmbed embed = null , IEnumerable < IMention > mentions = null ) = >
2020-06-21 13:11:18 +00:00
// Passing an empty list blocks all mentions by default (null allows all through)
channel . SendMessageAsync ( content , embed : embed , mentions : mentions ? ? new IMention [ 0 ] ) ;
2020-06-20 15:33:10 +00:00
// This doesn't do anything by itself (DiscordMember.SendMessageAsync doesn't take a mentions argument)
// It's just here for consistency so we don't use the standard SendMessageAsync method >.>
public static Task < DiscordMessage > SendMessageFixedAsync ( this DiscordMember member , string content = null , DiscordEmbed embed = null ) = >
member . SendMessageAsync ( content , embed : embed ) ;
2020-06-24 14:47:34 +00:00
public static bool TryGetCachedUser ( this DiscordClient client , ulong id , out DiscordUser user )
{
user = null ;
var cache = ( ConcurrentDictionary < ulong , DiscordUser > ) typeof ( BaseDiscordClient )
. GetProperty ( "UserCache" , BindingFlags . Instance | BindingFlags . NonPublic )
? . GetValue ( client ) ;
return cache ! = null & & cache . TryGetValue ( id , out user ) ;
2020-06-28 18:26:14 +00:00
}
public static DiscordColor ? ToDiscordColor ( this string color )
{
if ( int . TryParse ( color , NumberStyles . HexNumber , null , out var colorInt ) )
return new DiscordColor ( colorInt ) ;
throw new ArgumentException ( $"Invalid color string '{color}'." ) ;
}
public static bool HasMentionPrefix ( string content , ref int argPos , out ulong mentionId )
{
mentionId = 0 ;
// Roughly ported from Discord.Commands.MessageExtensions.HasMentionPrefix
if ( string . IsNullOrEmpty ( content ) | | content . Length < = 3 | | ( content [ 0 ] ! = '<' | | content [ 1 ] ! = '@' ) )
return false ;
int num = content . IndexOf ( '>' ) ;
if ( num = = - 1 | | content . Length < num + 2 | | content [ num + 1 ] ! = ' ' | | ! TryParseMention ( content . Substring ( 0 , num + 1 ) , out mentionId ) )
return false ;
argPos = num + 2 ;
return true ;
}
public static bool TryParseMention ( this string potentialMention , out ulong id )
{
if ( ulong . TryParse ( potentialMention , out id ) ) return true ;
var match = USER_MENTION . Match ( potentialMention ) ;
if ( match . Success & & match . Index = = 0 & & match . Length = = potentialMention . Length )
{
id = ulong . Parse ( match . Groups [ 1 ] . Value , NumberStyles . None , CultureInfo . InvariantCulture ) ;
return true ;
}
return false ;
}
2020-07-18 15:06:02 +00:00
public static IEnumerable < IMention > ParseAllMentions ( this string input , bool allowEveryone = false , DiscordGuild guild = null )
2020-06-28 18:26:14 +00:00
{
var mentions = new List < IMention > ( ) ;
mentions . AddRange ( USER_MENTION . Matches ( input )
. Select ( x = > new UserMention ( ulong . Parse ( x . Groups [ 1 ] . Value ) ) as IMention ) ) ;
2020-07-18 15:06:02 +00:00
// Only allow role mentions through where the role is actually listed as *mentionable*
// (ie. any user can @ them, regardless of permissions)
// Still let the allowEveryone flag override this though (privileged users can @ *any* role)
// Original fix by Gwen
2020-06-28 18:26:14 +00:00
mentions . AddRange ( ROLE_MENTION . Matches ( input )
2020-07-18 15:06:02 +00:00
. Select ( x = > ulong . Parse ( x . Groups [ 1 ] . Value ) )
. Where ( x = > allowEveryone | | guild ! = null & & guild . GetRole ( x ) . IsMentionable )
. Select ( x = > new RoleMention ( x ) as IMention ) ) ;
2020-06-28 18:26:14 +00:00
if ( EVERYONE_HERE_MENTION . IsMatch ( input ) & & allowEveryone )
mentions . Add ( new EveryoneMention ( ) ) ;
return mentions ;
}
public static string EscapeMarkdown ( this string input )
{
Regex pattern = new Regex ( @"[*_~>`(||)\\]" , RegexOptions . Multiline ) ;
if ( input ! = null ) return pattern . Replace ( input , @"\$&" ) ;
else return input ;
2020-06-24 14:47:34 +00:00
}
2020-07-02 16:29:04 +00:00
2020-07-05 10:55:21 +00:00
public static string EscapeBacktickPair ( this string input ) {
Regex doubleBacktick = new Regex ( @"``" , RegexOptions . Multiline ) ;
//Run twice to catch any pairs that are created from the first pass, pairs shouldn't be created in the second as they are created from odd numbers of backticks, even numbers are all caught on the first pass
2020-08-12 14:51:59 +00:00
if ( input ! = null ) return doubleBacktick . Replace ( doubleBacktick . Replace ( input , @"` `" ) , @"` `" ) ;
2020-07-05 10:55:21 +00:00
else return input ;
}
2020-07-02 16:29:04 +00:00
public static Task < DiscordUser > GetUser ( this DiscordRestClient client , ulong id ) = >
WrapDiscordCall ( client . GetUserAsync ( id ) ) ;
public static Task < DiscordUser > GetUser ( this DiscordClient client , ulong id ) = >
WrapDiscordCall ( client . GetUserAsync ( id ) ) ;
public static Task < DiscordChannel > GetChannel ( this DiscordRestClient client , ulong id ) = >
WrapDiscordCall ( client . GetChannelAsync ( id ) ) ;
public static Task < DiscordChannel > GetChannel ( this DiscordClient client , ulong id ) = >
WrapDiscordCall ( client . GetChannelAsync ( id ) ) ;
public static Task < DiscordGuild > GetGuild ( this DiscordRestClient client , ulong id ) = >
WrapDiscordCall ( client . GetGuildAsync ( id ) ) ;
public static Task < DiscordGuild > GetGuild ( this DiscordClient client , ulong id ) = >
WrapDiscordCall ( client . GetGuildAsync ( id ) ) ;
public static Task < DiscordMember > GetMember ( this DiscordRestClient client , ulong guild , ulong user )
{
async Task < DiscordMember > Inner ( ) = >
await ( await client . GetGuildAsync ( guild ) ) . GetMemberAsync ( user ) ;
return WrapDiscordCall ( Inner ( ) ) ;
}
public static Task < DiscordMember > GetMember ( this DiscordClient client , ulong guild , ulong user )
{
async Task < DiscordMember > Inner ( ) = >
await ( await client . GetGuildAsync ( guild ) ) . GetMemberAsync ( user ) ;
return WrapDiscordCall ( Inner ( ) ) ;
}
public static Task < DiscordMember > GetMember ( this DiscordGuild guild , ulong user ) = >
WrapDiscordCall ( guild . GetMemberAsync ( user ) ) ;
public static Task < DiscordMessage > GetMessage ( this DiscordChannel channel , ulong id ) = >
WrapDiscordCall ( channel . GetMessageAsync ( id ) ) ;
public static Task < DiscordMessage > GetMessage ( this DiscordRestClient client , ulong channel , ulong message ) = >
WrapDiscordCall ( client . GetMessageAsync ( channel , message ) ) ;
2020-07-22 08:07:18 +00:00
public static DiscordGuild GetGuild ( this DiscordShardedClient client , ulong id )
{
DiscordGuild guild ;
foreach ( DiscordClient shard in client . ShardClients . Values )
{
shard . Guilds . TryGetValue ( id , out guild ) ;
if ( guild ! = null ) return guild ;
}
return null ;
}
public static async Task < DiscordChannel > GetChannel ( this DiscordShardedClient client , ulong id , ulong? guildId = null )
{
// we need to know the channel's guild ID to get the cached guild object, so we grab it from the API
if ( guildId = = null ) {
var guild = await WrapDiscordCall ( client . ShardClients . Values . FirstOrDefault ( ) . GetChannelAsync ( id ) ) ;
if ( guild ! = null ) guildId = guild . Id ;
else return null ; // we probably don't have the guild in cache if the API doesn't give it to us
}
return client . GetGuild ( guildId . Value ) . GetChannel ( id ) ;
}
2020-07-02 16:29:04 +00:00
private static async Task < T > WrapDiscordCall < T > ( Task < T > t )
where T : class
{
try
{
return await t ;
}
catch ( NotFoundException )
{
return null ;
}
catch ( UnauthorizedException )
{
return null ;
}
}
2020-07-07 18:57:22 +00:00
public static DiscordEmbedBuilder WithSimpleLineContent ( this DiscordEmbedBuilder eb , IEnumerable < string > lines )
{
static int CharacterLimit ( int pageNumber ) = >
// First chunk goes in description (2048 chars), rest go in embed values (1000 chars)
pageNumber = = 0 ? 2048 : 1000 ;
var linesWithEnding = lines . Select ( l = > $"{l}\n" ) ;
var pages = StringUtils . JoinPages ( linesWithEnding , CharacterLimit ) ;
// Add the first page to the embed description
if ( pages . Count > 0 )
eb . WithDescription ( pages [ 0 ] ) ;
// Add the rest to blank-named (\u200B) fields
for ( var i = 1 ; i < p ages . Count ; i + + )
eb . AddField ( "\u200B" , pages [ i ] ) ;
return eb ;
}
2020-07-10 14:35:52 +00:00
public static string BreakLinkEmbeds ( this string str ) = >
// Encases URLs in <brackets>
UNBROKEN_LINK_REGEX . Replace ( str , match = >
{
// Don't break already-broken links
// The regex will include the brackets in the match, so we can check for their presence here
if ( match . Value . StartsWith ( "<" ) & & match . Value . EndsWith ( ">" ) )
return match . Value ;
return $"<{match.Value}>" ;
} ) ;
2020-02-12 14:16:19 +00:00
}
2020-08-12 14:51:59 +00:00
}