aboutsummaryrefslogtreecommitdiff
path: root/src/client/context.rs
Commit message (Collapse)AuthorAgeFilesLines
* Add From impls for Game, generify Game paramsZeyla Hellyer2018-08-011-10/+10
| | | | | Add more `impl From<T> for Game` implementations, and make `Into<Game>` trait bounds for all function parameters accepting a Game.
* Deprecate Context::edit_profileZeyla Hellyer2018-07-311-0/+1
| | | | This method won't exist in v0.6.x.
* Remove a usage of Clone::cloneZeyla Hellyer2018-04-261-2/+2
|
* Refactor imports/exports to use nested groups and better formattingacdenisSK2018-03-291-2/+4
|
* Remove useless clones (#292)Maiddog2018-03-171-1/+1
|
* Fix broken docs links caused by model mod changesZeyla Hellyer2018-01-311-12/+12
| | | | | Fix broken links caused by the `model` module changes in v0.5.0, which split up the module into sub-modules for better organization.
* Use an InterMessage to communicate over gatewayZeyla Hellyer2018-01-181-2/+3
| | | | | | | Instead of communicating over the gateway in a split form of a `serde_json::Value` or a `client::bridge::gateway::ShardClientMessage`, wrap them both into a single enum for better interaction between the client, gateway, and voice modules.
* Move `VecMap` to `utils`acdenisSK2018-01-021-3/+3
| | | | This also fixes no-builder compilation
* Improve performance of builders even furtheracdenisSK2017-12-271-3/+3
| | | | | | By negating hashing altogether. The increase is around 1000-ish nanoseconds saved.
* Break up the model moduleZeyla Hellyer2017-12-161-13/+14
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | The `model` module has historically been one giant module re-exporting all of the model types, which is somewhere around 100 types. This can be a lot to look at for a new user and somewhat overwhelming, especially with a large number of fine-grained imports from the module. The module is now neatly split up into submodules, mostly like it has been internally since the early versions of the library. The submodules are: - application - channel - error - event - gateway - guild - id - invite - misc - permissions - prelude - user - voice - webhook Each submodule contains types that are "owned" by the module. For example, the `guild` submodule contains, but not limited to, Emoji, AuditLogsEntry, Role, and Member. `channel` contains, but not limited to, Attachment, Embed, Message, and Reaction. Upgrade path: Instead of glob importing the models via `use serenity::model::*;`, instead glob import via the prelude: ```rust use serenity::model::prelude::*; ``` Instead of importing from the root model module: ```rust use serenity::model::{Guild, Message, OnlineStatus, Role, User}; ``` instead import from the submodules like so: ```rust use serenity::model::channel::Message; use serenity::model::guild::{Guild, Role}; use serenity::model::user::{OnlineStatus, User}; ```
* Make `Context::edit_profile` slightly efficientacdenisSK2017-12-141-3/+3
|
* Re-order use statements alphabeticallyZeyla Hellyer2017-11-111-8/+8
|
* Merge v0.4.3acdenisSK2017-11-041-0/+6
|\
| * Fix doctests for a variety of feature targetsZeyla Hellyer2017-11-011-0/+6
| |
| * `to_owned` -> `to_string`acdenisSK2017-10-011-5/+5
| |
* | Redo client internals + gatewayZeyla Hellyer2017-11-031-32/+33
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | This commit is a rewrite of the client module's internals and the gateway. The main benefit of this is that there is either 0 or 1 lock retrievals per event received, and the ability to utilize the ShardManager both internally and in userland code has been improved. The primary rework is in the `serenity::client` module, which now includes a few more structures, some changes to existing ones, and more functionality (such as to the `ShardManager`). The two notable additions to the client-gateway bridge are the `ShardMessenger` and `ShardManagerMonitor`. The `ShardMessenger` is a simple-to-use interface for users to use to interact with shards. The user is given one of these in the `serenity::client::Context` in dispatches to the `serenity::client::EventHandler`. This can be used for updating the presence of a shard, sending a guild chunk message, or sending a user's defined WebSocket message. The `ShardManagerMonitor` is a loop run in its own thread, potentially the main thread, that is responsible for receiving messages over an mpsc channel on what to do with shards via the `ShardManager`. For example, it will receive a message to shutdown a single shard, restart a single shard, or shutdown the entire thing. Users, in most applications, will not interact with the `ShardManagerMonitor`. Users using the `serenity::client::Client` interact with only the `ShardMessenger`. The `ShardManager` is now usable by the user and is available to them, and contains public functions for shutdowns, initializations, restarts, and complete shutdowns of shards. It contains utility functions like determining whether the `ShardManager` is responsible for a shard of a given ID and the IDs of shards currently active (having an associated `ShardRunner`). It can be found on `serenity::client::Client::shard_manager`. Speaking of the `ShardRunner`, it no longer owns a clone of an Arc to its assigned `serenity::gateway::Shard`. It now completely owns the Shard. This means that in order to open the shard, a `ShardRunner` no longer has to repeatedly retrieve a lock to it. This reduces the number of lock retrievals per event dispatching cycle from 3 or 4 depending on event type to 0 or 1 depending on whether it's a message create _and_ if the framework is in use. To interact with the Shard, one must now go through the previously mentioned `ShardMessenger`, which the `ShardRunner` will check for messages from on a loop. `serenity::client::Context` is now slightly different. Instead of the `shard` field being `Arc<Mutex<Shard>>`, it is an instance of a `ShardMessenger`. The interface is the same (minus losing some Shard-specific methods like `latency`), and `Context`'s shortcuts still exist (like `Context::online` or `Context::set_game`). It now additionally includes a `Context::shard_id` field which is a u64 containing the ID of the shard that the event was dispatched from. `serenity::client::Client` has one changed field name, one field that is now public, and a new field. `Client::shard_runners` is now `Client::shard_manager` of type `Arc<Mutex<ShardManager>>`. The `Client::token` field is now public. This can, for example, be mutated on token resets if you know what you're doing. `Client::ws_uri` is new and contains the URI for shards to use when connecting to the gateway. Otherwise, the Client's usage is unchanged. `serenity::gateway::Shard` has a couple of minor changes and many more public methods and fields. The `autoreconnect`, `check_heartbeat`, `handle_event`, `heartbeat`, `identify`, `initialize`, `reset`, `resume`, `reconnect`, and `update_presence` methods are now public. The `token` structfield is now public. There are new getters for various structfields, such as `heartbeat_instants` and `last_heartbeat_ack`. The breaking change on the `Shard` is that `Shard::handle_event` now takes an event by reference and, instead of returning `Result<Option<Event>>`, it now returns `Result<Option<ShardAction>>`. `serenity::gateway::ShardAction` is a light enum determining an action that someone _should_/_must_ perform on the shard, e.g. reconnecting or identifying. This is determined by `Shard::handle_event`. In total, there aren't too many breaking changes that most of userland use cases has to deal with -- at most, changing some usage of `Context`. Retrieving information like a Shard's latency is currently not possible anymore but work will be done to make this functionality available again.
* | Make the Client return a ResultZeyla Hellyer2017-11-031-10/+32
| | | | | | | | | | | | | | | | The client now returns a Result in preparation of a future commit. Upgrade path: Handle the case of an error via pattern matching, or unwrap the Result.
* | Remove `on_` prefix to EventHandler tymethodsZeyla Hellyer2017-10-221-10/+10
| | | | | | | | | | It was voted that the `on_` prefix is unnecessary, so these have been dropped.
* | Remove setting of the afk field in shardsZeyla Hellyer2017-10-191-7/+7
| |
* | Slightly improve performance of buildersZeyla Hellyer2017-10-181-7/+9
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Builders would keep a `serde_json::Map<String, Value>`, which would require re-creating owned strings for the same parameter multiple times in some cases, depending on builder defaults and keying strategies. This commit uses a `std::collections::HashMap<&'static str, Value>` internally, and moves over values to a `serde_json::Map<String, Value>` when it comes time to sending them to the appropriate `http` module function. This saves the number of heap-allocated string creations on most builders, with specific performance increase on `builder::CreateMessage` and `builder::CreateEmbed` & co.
* | Switch to parking_lot::{Mutex, RwLock}Zeyla Hellyer2017-10-101-1/+1
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Switch to the `parking_lot` crate's implementations of `std::sync::Mutex` and `std::sync::RwLock`, which are more efficient. A writeup on why `parking_lot` is more efficient can be read here: <https://github.com/Amanieu/parking_lot> Upgrade path: Modify `mutex.lock().unwrap()` usage to `mutex.lock()` (not needing to unwrap or handle a result), and `rwlock.read().unwrap()`/`rwlock.write().unwrap()` usage to `rwlock.read()` and `rwlock.write()`. For example, modify: ```rust use serenity::CACHE; println!("{}", CACHE.read().unwrap().user.id); ``` to: ```rust use serenity::CACHE; println!("{}", CACHE.read().user.id); ```
* | `to_owned` -> `to_string`acdenisSK2017-10-091-5/+5
|/
* Remove tokio usageZeyla Hellyer2017-09-211-6/+1
|
* Fix block on spawning multiple shardsZeyla Hellyer2017-09-181-0/+1
| | | | | | | | | | | | When spawning multiple shards (via an equal number of futures - one per shard) joined on a core.run use, the very first future executed would block forever due to a sync, blocking `monitor_shard` use. While this defeats the purpose of tokio, this was meant to be a first step to an async serenity implementation. To "fix" this blocking call until a deeper async implementation is made, spawn a new thread per tokio core (and thus per shard). This causes the same expected behaviour, just with multiple threads like before.
* Fix compiles of a variety of feature combinationsZeyla Hellyer2017-09-181-1/+2
| | | | | This fixes compilation errors and warnings when compiling a mixture of non-default feature targets.
* Copy some methods from Command to Group (#164)Maiddog2017-09-111-1/+4
|
* Add `Context::handle`acdenisSK2017-09-111-1/+5
|
* Prevent malformed opus data from crashing the bot process (#149)Maiddog2017-08-271-17/+19
|
* Add ability to play DCA and Opus files. (#148)Maiddog2017-08-271-1/+1
|
* Revamp `RwLock` usage in the libacdenisSK2017-08-241-17/+17
| | | | Also not quite sure if they goofed rustfmt or something, but its changes it did were a bit bizarre.
* rustfmtacdenisSK2017-07-271-32/+29
|
* Switch to tokio for events (#122)Alex Lyon2017-07-141-10/+11
|
* Fix doc testsacdenisSK2017-07-021-79/+125
|
* Add a `quit` function`acdenisSK2017-06-301-0/+11
| | | | Fixes #70
* Switch from #[doc(hidden)] to pub(crate)alex2017-06-141-8/+1
| | | | | | Switch from using `#[doc(hidden)]` to hide some internal functions to `pub(crate)`. The library now requires rustc 1.18.
* Remove Context::{channel_id, queue}Zeyla Hellyer2017-06-131-12/+1
| | | | | | | | | The `channel_id` field on Context is no longer required internally, and is no longer of use to userland as event handlers are given the channel ID in some way where possible. `queue` is a remnant from when the Context was the primary way to interact with the REST API.
* Upgrade rust-websocket, rust-openssl, and hyperZeyla Hellyer2017-06-071-16/+16
| | | | | | | | | | | | | | | | Upgrade `rust-websocket` to v0.20, maintaining use of its sync client. This indirectly switches from `rust-openssl` v0.7 - which required openssl-1.0 on all platforms - to `native-tls`, which allows for use of schannel on Windows, Secure Transport on OSX, and openssl-1.1 on other platforms. Additionally, since hyper is no longer even a dependency of rust-websocket, we can safely and easily upgrade to `hyper` v0.10 and `multipart` v0.12. This commit is fairly experimental as it has not been tested on a long-running bot.
* Deprecate Client::login, add Client::newZeyla Hellyer2017-06-061-10/+10
|
* Fix compilations across feature combinationsZeyla Hellyer2017-06-021-2/+4
|
* Add more examples and improve some othersZeyla Hellyer2017-05-231-25/+141
| | | | | Add examples to some functions, and update some of the old examples to use the `?` operator instead of unwrapping.
* Restructure modulesZeyla Hellyer2017-05-221-8/+10
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Modules are now separated into a fashion where the library can be used for most use cases, without needing to compile the rest. The core of serenity, with no features enabled, contains only the struct (model) definitions, constants, and prelude. Models do not have most functions compiled in, as that is separated into the `model` feature. The `client` module has been split into 3 modules: `client`, `gateway`, and `http`. `http` contains functions to interact with the REST API. `gateway` contains the Shard to interact with the gateway, requiring `http` for retrieving the gateway URL. `client` requires both of the other features and acts as an abstracted interface over both the gateway and REST APIs, handling the event loop. The `builder` module has been separated from `utils`, and can now be optionally compiled in. It and the `http` feature are required by the `model` feature due to a large number of methods requiring access to them. `utils` now contains a number of utilities, such as the Colour struct, the `MessageBuilder`, and mention parsing functions. Each of the original `ext` modules are still featured, with `cache` not requiring any feature to be enabled, `framework` requiring the `client`, `model`, and `utils`, and `voice` requiring `gateway`. In total the features and their requirements are: - `builder`: none - `cache`: none - `client`: `gateway`, `http` - `framework`: `client`, `model`, `utils` - `gateway`: `http` - `http`: none - `model`: `builder`, `http` - `utils`: none - `voice`: `gateway` The default features are `builder`, `cache`, `client`, `framework`, `gateway`, `model`, `http`, and `utils`. To help with forwards compatibility, modules have been re-exported from their original locations.
* Switch to using serde for deserializationZeyla Hellyer2017-04-111-9/+6
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | The current build system is rudimentary, incomplete, and rigid, offering little in the way of customizing decoding options. To solve this, switch to using serde-derive with custom Deserialization implementations. This allows very simple deserialization when special logic does not need to be applied, yet allows us to implement our own deserialization logic when required. The problem with the build system was that it built enums and structs from YAML files. This is not so good, because it requires creating a custom build system (which was rudimentary), creating "special struct configs" when logic needed to be ever so slightly extended (rigid), and if special logic needed to be applied, a custom deserialization method would have been needed to be made anyway (incomplete). To solve this, switch to serde-derive and implementing Deserialize ourselves where required. This reduces YAML definitions that might look like: ```yaml --- name: Group description: > A group channel, potentially including other users, separate from a [`Guild`]. [`Guild`]: struct.Guild.html fields: - name: channel_id description: The Id of the group channel. from: id type: ChannelId - name: icon description: The optional icon of the group channel. optional: true type: string - name: last_message_id description: The Id of the last message sent. optional: true type: MessageId - name: last_pin_timestamp description: Timestamp of the latest pinned message. optional: true type: string - name: name description: The name of the group channel. optional: true type: string - name: owner_id description: The Id of the group channel creator. type: UserId - name: recipients description: Group channel's members. custom: decode_users t: UserId, Arc<RwLock<User>> type: hashmap ``` to: ```rs /// A group channel - potentially including other [`User`]s - separate from a /// [`Guild`]. /// /// [`Guild`]: struct.Guild.html /// [`User`]: struct.User.html pub struct Group { /// The Id of the group channel. #[serde(rename="id")] pub channel_id: ChannelId, /// The optional icon of the group channel. pub icon: Option<String>, /// The Id of the last message sent. pub last_message_id: Option<MessageId>, /// Timestamp of the latest pinned message. pub last_pin_timestamp: Option<String>, /// The name of the group channel. pub name: Option<String>, /// The Id of the group owner. pub owner_id: UserId, /// A map of the group's recipients. #[serde(deserialize_with="deserialize_users")] pub recipients: HashMap<UserId, Arc<RwLock<User>>>, } ``` This is much simpler and does not have as much boilerplate. There should not be any backwards incompatible changes other than the old, public - yet undocumented (and hidden from documentation) - decode methods being removed. Due to the nature of this commit, field names may be incorrect, and will need to be corrected as deserialization errors are found.
* Remove selfbot supportZeyla Hellyer2017-04-051-5/+1
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | While selfbots have always been "roughly tolerated", lately they have been tolerated to less of a degree. The simple answer is to no longer support selfbots in any form. This is done for a few of reasons: 1) in anticipation of selfbots no longer being tolerated; 2) there are few reasons why one should make a selfbot in Rust and not a scripting language; 3) there are alternatives (i.e. discord-rs) that still support userbots. Selfbots are simply not a goal of the maintainer of serenity. Upgrade path: Don't use selfbots with serenity. Use discord-rs instead. The following has been removed: Enums: - `RelationshipType` Structs: - `FriendSourceFlags` - `ReadState` - `Relationship` - `SearchResult` - `SuggestionReason` - `Tutorial` - `UserConnection` - `UserGuildSettings` - `UserSettings` Removed the following fields: - `CurrentUser::mobile` - Ready::{ analytics_token, experiments, friend_suggestion_count, notes, read_state, relationships, tutorial, user_guild_settings, user_settings, } Removed the following methods: - `Client::login_user` Deprecated `Client::login_bot` in favour of `Client::login`. Removed `client::LoginType`. The following no longer take a `login_type` parameter: - `Context::new` - `Shard::new` `Shard::sync_guilds` has been removed. The `client::Error::{InvalidOperationAsBot, InvalidOperationAsUser}` variants have been removed. The following event handlers on `Client` have been removed: - `on_friend_suggestion_create` - `on_friend_suggestion_delete` - `on_relationship_add` - `on_relationship_remove` - `on_user_guild_settings_update` - `on_note_update` - `on_user_settings_update` The following `client::rest` functions have been removed: - `ack_message` - `edit_note` - `get_user_connections` - `search_channel_messages` - `search_guild_messages` The following `client::rest::ratelimiting::Route` variants have been removed: - `ChannelsIdMessagesSearch` - `GuildsIdMessagesSearch` - `UsersMeConnections` The following fields on `ext::cache::Cache` have been removed: - `guild_settings` - `relationships` - `settings` while the following methods have also been removed: - `update_with_relationship_add` - `update_with_relationship_remove` - `update_with_user_guild_settings_update` - `update_with_user_note_update` - `update_with_user_settings_update` The following methods have been removed across models: - `ChannelId::{ack, search}` - `Channel::{ack, search}` - `Group::{ack, search}` - `GuildChannel::{ack, search}` - `GuildId::{search, search_channels}` - `Guild::{search, search_channels}` - `Message::ack` - `PartialGuild::{search, search_channels}` - `PrivateChannel::{ack, search}` - `UserId::{delete_note, edit_note}` - `User::{delete_note, edit_note}` The following events in `model::events` have been removed: - `FriendSuggestionCreateEvent` - `FriendSuggestionDeleteEvent` - `MessageAckEvent` - `RelationshipAddEvent` - `RelationshipRemoveEvent` - `UserGuildSettingsUpdateEvent` - `UserNoteUpdateEvent` - `UserSettingsUpdateEvent` Consequently, the following variants on `model::event::Event` have been removed: - `FriendSuggestionCreate` - `FriendSuggestionDelete` - `MessageAdd` - `RelationshipAdd` - `RelationshipRemove` - `UserGuildSettingUpdate` - `UserNoteUpdate` - `UserSettingsUpdate` The `utils::builder::Search` search builder has been removed.
* Pass by reference where possibleZeyla Hellyer2017-02-281-1/+1
| | | | | | | A lot of the `rest` methods took - for example a Map - by value, where they could instead take a reference. While this only prevents one clone in the library, user-land code should no longer need to clone maps when using the `rest` module.
* Add 'say' to Group, GuildChannel, PrivateChannelZeyla Hellyer2017-02-131-1/+1
|
* Remove most Context methodsZeyla Hellyer2017-02-121-821/+7
| | | | | | Most of the methods in the Context were for interacting with the related ChannelId, but these methods have been re-implemented on ChannelId itself, and is now the preferred (and now only) way to interact with it.
* Optimize cachingZeyla Hellyer2017-02-091-6/+6
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Improve the cache by keeping track of new maps, making other maps have `Arc<RwLock>` values, optimizing already-existing methods, and take advantage of new, more efficient retrievals (e.g. simply keying a value from a map rather than iterating over vecs or maps and then itering over another vec). Keep track of two new maps in the cache: - **channels**: a map of all guild channels that exist, so that they can be efficiently found, and so a message's guild can be efficiently found - **users**: a map of all users that exist, so that it can be shared across all members and presences Other cache fields now have `Arc<RwLock>` values: - `groups` - `guilds` - `private_channels` `Cache::unavailable_guilds` is now a `HashSet<GuildId>` instead of a `Vec<GuildId>`. This should slightly optimize removals/insertions for large bots. `ext::cache::ChannelRef` has been removed as it became equivilant in functionality to `model::Channel`. Also, `model::Channel` now has all variant data encased in `Arc<RwLock>`s. E.g., `Channel::Group(Group)` is now `Channel::Group(Arc<RwLock<Group>>)`. Some model struct fields are now wrapped in an `Arc<RwLock>`. These are: - `Group::recipients`: `HashMap<UserId, User>` -> `HashMap<UserId, Arc<RwLock<User>>>` - `Guild::channels`: `HashMap<ChannelId, GuildChannel>` -> `HashMap<ChannelId, Arc<RwLock<GuildChannel>>>` - `Member::user`: `User` -> `Arc<RwLock<User>>` - `PrivateChannel::recipient`: `User` -> `Arc<RwLock<User>>` Some (cache-enabled) event handler signatures have changed to use `Arc<RwLock>`s: - `Client::on_call_delete` - `Client::on_call_update` - `Client::on_guild_delete` - `Client::on_guild_update` Many function signatures have changed: - `Cache::get_call` now returns a `Option<Arc<RwLock<Call>>>` instead of a `Option<&Call>` - `Cache::get_channel` now returns a `Option<Channel>` instead of a `Option<ChannelRef>`. This now also retrieves directly from the `Guild::channels` instead of iterating over guilds' for a guild channel - `Cache::get_guild` now returns a `Option<Arc<RwLock<Guild>>>` instead of a `Option<&Guild>` - `Cache::get_guild_channel` now returns a `Option<Arc<RwLock<GuildChannel>>>` instead of a `Option<&GuildChannel>` - `Cache::get_group` now returns a `Option<Arc<RwLock<Group>>>` instead of a `Option<&Group>` - `Cache::get_member` now returns a `Option<Member>` instead of a `Option<&Member>`, due to guilds being behind a lock themselves - `Cache::get_role` now returns a `Option<Role>` instead of a `Option<&Role>` for the above reason - `Cache::get_user` now returns a `Option<Arc<RwLock<User>>>` instead of a `Option<&User>` - `GuildId::find` now returns a `Option<Arc<RwLock<Guild>>>` instead of a `Option<Guild>` - `UserId::find` now returns a `Option<Arc<RwLock<User>>>` instead of a `Option<User>` - `Member::display_name` now returns a `Cow<String>` instead of a `&str` A new cache method has been added, `Cache::get_private_channel`, to retrieve a `PrivateChannel`. The `Display` formatter for `Channel` has been optimized to not clone.
* Update examples for OOP updateAustin Hellyer2017-01-261-4/+4
|
* Fix docs linksAustin Hellyer2017-01-241-9/+10
|
* Switch to a mostly-fully OOP approachAustin Hellyer2017-01-231-1131/+275
| | | | | | The context is now strictly in relation to the context of the current channel related to the event, if any. See Context::say for a list of events that the context can be used for.