Fix unneeded code from Nyxx; Move token check at the top of constructor; Add userCachePolicyLocation to CacheOptions; Fix docs typos; Fix sticker deserialization

This commit is contained in:
Szymon Uglis 2021-04-19 21:37:51 +02:00
parent 8e8d51be73
commit 99f14e1174
No known key found for this signature in database
GPG key ID: AA55C76D0E11A7E3
11 changed files with 34 additions and 45 deletions

View file

@ -13,6 +13,9 @@ class CacheOptions {
/// Defines which channel entities are preserved in cache.
CachePolicy<IChannel> channelCachePolicy = ChannelCachePolicy.def;
/// Defines in which places user can be cached
CachePolicyLocation userCachePolicyLocation = CachePolicyLocation();
}
/// Optional client settings which can be used when creating new instance

View file

@ -107,6 +107,9 @@ class NyxxRest extends INyxx {
bool ignoreExceptions = true,
bool useDefaultLogger = true,
Level? defaultLoggerLogLevel}) {
if (_token.isEmpty) {
throw MissingTokenError();
}
if (useDefaultLogger) {
Logger.root.level = defaultLoggerLogLevel ?? Level.ALL;
@ -117,11 +120,7 @@ class NyxxRest extends INyxx {
});
}
this._logger.info("Starting bot with pid: $pid");
if (_token.isEmpty) {
throw MissingTokenError();
}
this._logger.info("Starting bot with pid: $pid. To stop the bot gracefully send SIGTERM or SIGKILL");
if (!Platform.isWindows) {
ProcessSignal.sigterm.watch().forEach((event) async {
@ -323,13 +322,13 @@ class Nyxx extends NyxxRest {
this._ws = _ConnectionManager(this);
}
/// The client"s uptime.
/// The client's uptime.
Duration get uptime => DateTime.now().difference(_startTime);
/// [DateTime] when client was started
DateTime get startTime => _startTime;
/// This endpoint is only for Public guilds if bot is not int the guild.
/// This endpoint is only for public guilds if bot is not int the guild.
Future<GuildPreview> fetchGuildPreview(Snowflake guildId) async =>
this._httpEndpoints.fetchGuildPreview(guildId);
@ -351,29 +350,6 @@ class Nyxx extends NyxxRest {
Future<User> fetchUser(Snowflake userId) =>
this._httpEndpoints.fetchUser(userId);
// /// Creates new guild with provided builder.
// /// Only for bots with less than 10 guilds otherwise it will return Future with error.
// ///
// /// ```
// /// var guildBuilder = GuildBuilder()
// /// ..name = "Example Guild"
// /// ..roles = [RoleBuilder()..name = "Example Role]
// /// var newGuild = await client.createGuild(guildBuilder);
// /// ```
// Future<Guild> createGuild(GuildBuilder builder) async {
// if (this.guilds.count >= 10) {
// return Future.error(ArgumentError("Guild cannot be created if bot is in 10 or more guilds"));
// }
//
// final response = await this._http._execute(BasicRequest._new("/guilds", method: "POST"));
//
// if (response is HttpResponseSuccess) {
// return Guild._new(this, response.jsonBody as Map<String, dynamic>);
// }
//
// return Future.error(response);
// }
/// Gets a webhook by its id and/or token.
/// If token is supplied authentication is not needed.
Future<Webhook> fetchWebhook(Snowflake id, {String token = ""}) =>
@ -421,7 +397,6 @@ class Nyxx extends NyxxRest {
await this._events.dispose();
await guilds.dispose();
await users.dispose();
await guilds.dispose();
this._logger.info("Exiting...");
exit(0);

View file

@ -58,7 +58,7 @@ class DMChannel extends IChannel implements TextChannel {
client._httpEndpoints.fetchMessage(this.id, messageId);
@override
Future<Message?> getMessage(Snowflake id) => Future.value(this.messageCache[id]);
Message? getMessage(Snowflake id) => this.messageCache[id];
@override
Future<Message> sendMessage({dynamic content, EmbedBuilder? embed, List<AttachmentBuilder>? files, bool? tts, AllowedMentions? allowedMentions, MessageBuilder? builder, ReplyBuilder? replyBuilder}) =>

View file

@ -8,7 +8,7 @@ abstract class TextChannel implements IChannel, ISend {
MessageCache get messageCache;
/// Returns [Message] with given id from CACHE
Future<Message?> getMessage(Snowflake id);
Message? getMessage(Snowflake id);
/// Returns [Message] downloaded from API
Future<Message> fetchMessage(Snowflake id);

View file

@ -79,7 +79,7 @@ class TextGuildChannel extends GuildChannel implements TextChannel {
client._httpEndpoints.fetchMessage(this.id, messageId);
@override
Future<Message?> getMessage(Snowflake id) => Future.value(this.messageCache[id]);
Message? getMessage(Snowflake id) => this.messageCache[id];
@override
Future<Message> sendMessage({dynamic content, EmbedBuilder? embed, List<AttachmentBuilder>? files, bool? tts, AllowedMentions? allowedMentions, MessageBuilder? builder, ReplyBuilder? replyBuilder}) =>

View file

@ -408,7 +408,7 @@ class Guild extends SnowflakeEntity {
/// Request members from gateway. Requires privileged intents in order to work.
void requestChunking() => this.shard.requestMembers(this.id);
/// Allows to create new guil channel
/// Allows to create new guild channel
Future<IChannel> createChannel(ChannelBuilder channelBuilder) =>
this.client.httpEndpoints.createGuildChannel(this.id, channelBuilder);

View file

@ -191,7 +191,10 @@ class DMMessage extends Message {
if (user == null) {
final authorData = raw["author"] as Map<String, dynamic>;
this.author = User._new(client, authorData);
this.client.users.add(this.author.id, this.author);
if (client._cacheOptions.userCachePolicyLocation.objectConstructor) {
this.client.users[this.author.id] = this.author;
}
} else {
this.author = user;
}
@ -240,7 +243,10 @@ class GuildMessage extends Message {
this.author = Webhook._new(raw["author"] as Map<String, dynamic>, client);
} else {
this.author = User._new(client, raw["author"] as Map<String, dynamic>);
this.client.users[this.author.id] = this.author as User;
if (client._cacheOptions.userCachePolicyLocation.objectConstructor) {
this.client.users[this.author.id] = this.author as User;
}
}
if (raw["member"] != null) {

View file

@ -19,7 +19,7 @@ class Sticker extends SnowflakeEntity {
late final String asset;
/// Sticker preview asset hash
late final String assetPreview;
late final String? assetPreview;
/// Type of sticker format
late final StickerFormat format;
@ -36,7 +36,9 @@ class Sticker extends SnowflakeEntity {
this.description = raw["description"] as String;
this.tags = raw["tags"] as String?;
this.asset = raw["asset"] as String;
this.assetPreview = raw["preview_asset"] as String;
this.assetPreview = raw["preview_asset"] != null
? raw["preview_asset"] as String
: null;
this.format = StickerFormat.from(raw["format_type"] as int);
}
}

View file

@ -31,7 +31,7 @@ class Member extends SnowflakeEntity {
/// Voice state of member. Null if not connected to channel or voice state not cached
VoiceState? get voiceState => this.guild.getFromCache()?.voiceStates[this.id];
/// When the user starting boosting the guild
/// When the user starting boosting the guild
late DateTime? boostingSince;
// TODO: is everything okay?
@ -70,7 +70,7 @@ class Member extends SnowflakeEntity {
this.joinedAt = DateTime.parse(raw["joined_at"] as String).toUtc();
}
if (!client.users.hasKey(this.id)) {
if (!client.users.hasKey(this.id) && client._cacheOptions.userCachePolicyLocation.objectConstructor) {
final userRaw = raw["user"] as Map<String, dynamic>;
if (userRaw["id"] != null && userRaw.length != 1) {

View file

@ -80,7 +80,9 @@ class GuildMemberUpdateEvent {
this.member = _MemberCacheable(client, Snowflake(raw["d"]["user"]["id"]), guild);
final user = User._new(client, raw["d"]["user"] as Map<String, dynamic>);
client.users[user.id] = user;
if (client._cacheOptions.userCachePolicyLocation.event) {
client.users[user.id] = user;
}
final memberInstance = this.member.getFromCache();
if (memberInstance == null) {
@ -116,7 +118,7 @@ class GuildMemberAddEvent {
this.member = Member._new(client, raw["d"] as Map<String, dynamic>, this.guild.id);
this.user = User._new(client, raw["d"]["user"] as Map<String, dynamic>);
if (!client.users.hasKey(this.user.id)) {
if (!client.users.hasKey(this.user.id) && client._cacheOptions.userCachePolicyLocation.event) {
client.users[user.id] = user;
}
@ -235,7 +237,7 @@ class RoleUpdateEvent {
/// The guild that the member was banned from.
late final Cacheable<Snowflake, Guild> guild;
RoleUpdateEvent._new(Map<String, dynamic> raw, Nyxx client) {
this.guild = _GuildCacheable(client, Snowflake(raw["d"]["guild_id"]));
this.role = Role._new(client, raw["d"]["role"] as Map<String, dynamic>, this.guild.id);

View file

@ -75,7 +75,8 @@ abstract class MessageReactionEvent {
/// Channel on which event was fired
late final Cacheable<Snowflake, TextChannel> channel;
/// Reference to guild if event happend in guild
// TODO: Probably not working
/// Reference to guild if event happened in guild
late final Cacheable<Snowflake, Guild> guild;
/// Message reference