Merge pull request #43 from teloxide/cleanup

Cleanup
This commit is contained in:
Temirkhan Myrzamadi 2021-01-26 20:08:02 +06:00 committed by GitHub
commit d50884d9f1
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
14 changed files with 49 additions and 64 deletions

View file

@ -20,9 +20,9 @@ jobs:
include: include:
- rust: stable - rust: stable
features: "" features: "--features full"
- rust: beta - rust: beta
features: "" features: "--features full"
- rust: nightly - rust: nightly
features: "--all-features" features: "--all-features"

View file

@ -1,6 +1,6 @@
use teloxide_core::{ use teloxide_core::{
prelude::*, prelude::*,
types::{DiceEmoji, ParseMode}, types::{DiceEmoji, Me, ParseMode},
}; };
#[tokio::main] #[tokio::main]
@ -13,9 +13,9 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
.parse_mode(ParseMode::MarkdownV2) .parse_mode(ParseMode::MarkdownV2)
.auto_send(); .auto_send();
let me = bot.get_me().await?; let Me { user: me, .. } = bot.get_me().await?;
bot.send_dice(chat_id, DiceEmoji::Dice).await?; bot.send_dice(chat_id).emoji(DiceEmoji::Dice).await?;
bot.send_message(chat_id, format!("Hi, my name is **{}** 👋", me.first_name)) bot.send_message(chat_id, format!("Hi, my name is **{}** 👋", me.first_name))
.await?; .await?;

View file

@ -28,13 +28,13 @@ use crate::{
/// ```rust /// ```rust
/// use teloxide_core::{ /// use teloxide_core::{
/// requests::{Requester, RequesterExt}, /// requests::{Requester, RequesterExt},
/// types::User, /// types::Me,
/// Bot, /// Bot,
/// }; /// };
/// ///
/// # async { /// # async {
/// let bot = Bot::new("TOKEN").auto_send(); /// let bot = Bot::new("TOKEN").auto_send();
/// let myself: User = bot.get_me().await?; // No .send()! /// let myself: Me = bot.get_me().await?; // No .send()!
/// # Ok::<_, teloxide_core::RequestError>(()) }; /// # Ok::<_, teloxide_core::RequestError>(()) };
/// ``` /// ```
pub struct AutoSend<B> { pub struct AutoSend<B> {

View file

@ -11,7 +11,7 @@ use once_cell::sync::OnceCell;
use crate::{ use crate::{
payloads::GetMe, payloads::GetMe,
requests::{HasPayload, Request, Requester}, requests::{HasPayload, Request, Requester},
types::{ChatId, User, *}, types::{ChatId, Me, *},
}; };
/// `get_me` cache. /// `get_me` cache.
@ -20,7 +20,7 @@ use crate::{
/// response from `get_me` method. /// response from `get_me` method.
pub struct CacheMe<B> { pub struct CacheMe<B> {
bot: B, bot: B,
me: Arc<OnceCell<User>>, me: Arc<OnceCell<Me>>,
} }
impl<B> CacheMe<B> { impl<B> CacheMe<B> {
@ -52,7 +52,7 @@ impl<B> CacheMe<B> {
/// ///
/// Note: internally this uses [`Arc::make_mut`] so this will **not** /// Note: internally this uses [`Arc::make_mut`] so this will **not**
/// clear cache of clones of self. /// clear cache of clones of self.
pub fn clear(&mut self) -> Option<User> { pub fn clear(&mut self) -> Option<Me> {
Arc::make_mut(&mut self.me).take() Arc::make_mut(&mut self.me).take()
} }
} }
@ -79,7 +79,7 @@ where
fn get_me(&self) -> Self::GetMe { fn get_me(&self) -> Self::GetMe {
match self.me.get() { match self.me.get() {
Some(user) => CachedMeRequest(Inner::Ready(user.clone()), GetMe::new()), Some(me) => CachedMeRequest(Inner::Ready(me.clone()), GetMe::new()),
None => CachedMeRequest( None => CachedMeRequest(
Inner::Pending(self.bot.get_me(), Arc::clone(&self.me)), Inner::Pending(self.bot.get_me(), Arc::clone(&self.me)),
GetMe::new(), GetMe::new(),
@ -132,8 +132,8 @@ download_forward! {
pub struct CachedMeRequest<R: Request<Payload = GetMe>>(Inner<R>, GetMe); pub struct CachedMeRequest<R: Request<Payload = GetMe>>(Inner<R>, GetMe);
enum Inner<R: Request<Payload = GetMe>> { enum Inner<R: Request<Payload = GetMe>> {
Ready(User), Ready(Me),
Pending(R, Arc<OnceCell<User>>), Pending(R, Arc<OnceCell<Me>>),
} }
impl<R> Request for CachedMeRequest<R> impl<R> Request for CachedMeRequest<R>
@ -146,7 +146,7 @@ where
fn send(self) -> Self::Send { fn send(self) -> Self::Send {
let fut = match self.0 { let fut = match self.0 {
Inner::Ready(user) => future::Either::Left(ok(user)), Inner::Ready(me) => future::Either::Left(ok(me)),
Inner::Pending(req, cell) => future::Either::Right(Init(req.send(), cell)), Inner::Pending(req, cell) => future::Either::Right(Init(req.send(), cell)),
}; };
Send(fut) Send(fut)
@ -154,7 +154,7 @@ where
fn send_ref(&self) -> Self::SendRef { fn send_ref(&self) -> Self::SendRef {
let fut = match &self.0 { let fut = match &self.0 {
Inner::Ready(user) => future::Either::Left(ok(user.clone())), Inner::Ready(me) => future::Either::Left(ok(me.clone())),
Inner::Pending(req, cell) => { Inner::Pending(req, cell) => {
future::Either::Right(Init(req.send_ref(), Arc::clone(cell))) future::Either::Right(Init(req.send_ref(), Arc::clone(cell)))
} }
@ -175,15 +175,15 @@ impl<R: Request<Payload = GetMe>> HasPayload for CachedMeRequest<R> {
} }
} }
type ReadyUser<Err> = Ready<Result<User, Err>>; type ReadyMe<Err> = Ready<Result<Me, Err>>;
#[pin_project::pin_project] #[pin_project::pin_project]
pub struct Send<R: Request<Payload = GetMe>>( pub struct Send<R: Request<Payload = GetMe>>(
#[pin] future::Either<ReadyUser<R::Err>, Init<R::Send, User>>, #[pin] future::Either<ReadyMe<R::Err>, Init<R::Send, Me>>,
); );
impl<R: Request<Payload = GetMe>> Future for Send<R> { impl<R: Request<Payload = GetMe>> Future for Send<R> {
type Output = Result<User, R::Err>; type Output = Result<Me, R::Err>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project(); let this = self.project();
@ -193,11 +193,11 @@ impl<R: Request<Payload = GetMe>> Future for Send<R> {
#[pin_project::pin_project] #[pin_project::pin_project]
pub struct SendRef<R: Request<Payload = GetMe>>( pub struct SendRef<R: Request<Payload = GetMe>>(
#[pin] future::Either<ReadyUser<R::Err>, Init<R::SendRef, User>>, #[pin] future::Either<ReadyMe<R::Err>, Init<R::SendRef, Me>>,
); );
impl<R: Request<Payload = GetMe>> Future for SendRef<R> { impl<R: Request<Payload = GetMe>> Future for SendRef<R> {
type Output = Result<User, R::Err>; type Output = Result<Me, R::Err>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project(); let this = self.project();

View file

@ -765,13 +765,14 @@ impl Requester for Bot {
) )
} }
type CreateNewStickerSet = JsonRequest<payloads::CreateNewStickerSet>; type CreateNewStickerSet = MultipartRequest<payloads::CreateNewStickerSet>;
fn create_new_sticker_set<N, T, E>( fn create_new_sticker_set<N, T, E>(
&self, &self,
user_id: i32, user_id: i32,
name: N, name: N,
title: T, title: T,
sticker: InputSticker,
emojis: E, emojis: E,
) -> Self::CreateNewStickerSet ) -> Self::CreateNewStickerSet
where where
@ -781,7 +782,7 @@ impl Requester for Bot {
{ {
Self::CreateNewStickerSet::new( Self::CreateNewStickerSet::new(
self.clone(), self.clone(),
payloads::CreateNewStickerSet::new(user_id, name, title, emojis), payloads::CreateNewStickerSet::new(user_id, name, title, sticker, emojis),
) )
} }

View file

@ -25,8 +25,11 @@
//! let me = bot.get_me().await?; //! let me = bot.get_me().await?;
//! //!
//! bot.send_dice(chat_id).emoji(DiceEmoji::Dice).await?; //! bot.send_dice(chat_id).emoji(DiceEmoji::Dice).await?;
//! bot.send_message(chat_id, format!("Hi, my name is **{}** 👋", me.first_name)) //! bot.send_message(
//! .await?; //! chat_id,
//! format!("Hi, my name is **{}** 👋", me.user.first_name),
//! )
//! .await?;
//! # Ok::<_, Box<dyn std::error::Error>>(()) }; //! # Ok::<_, Box<dyn std::error::Error>>(()) };
//! ``` //! ```
//! //!

View file

@ -924,11 +924,11 @@ macro_rules! requester_forward {
(@method create_new_sticker_set $body:ident $ty:ident) => { (@method create_new_sticker_set $body:ident $ty:ident) => {
type CreateNewStickerSet = $ty![CreateNewStickerSet]; type CreateNewStickerSet = $ty![CreateNewStickerSet];
fn create_new_sticker_set<N, T, E>(&self, user_id: i32, name: N, title: T, emojis: E) -> Self::CreateNewStickerSet where N: Into<String>, fn create_new_sticker_set<N, T, E>(&self, user_id: i32, name: N, title: T, sticker: InputSticker, emojis: E) -> Self::CreateNewStickerSet where N: Into<String>,
T: Into<String>, T: Into<String>,
E: Into<String> { E: Into<String> {
let this = self; let this = self;
$body!(create_new_sticker_set this (user_id: i32, name: N, title: T, emojis: E)) $body!(create_new_sticker_set this (user_id: i32, name: N, title: T, sticker: InputSticker, emojis: E))
} }
}; };
(@method add_sticker_to_set $body:ident $ty:ident) => { (@method add_sticker_to_set $body:ident $ty:ident) => {

View file

@ -3,7 +3,7 @@
// edit `cg` instead. // edit `cg` instead.
use serde::Serialize; use serde::Serialize;
use crate::types::{InputFile, MaskPosition, True}; use crate::types::{InputSticker, MaskPosition, True};
impl_payload! { impl_payload! {
/// Use this method to create a new sticker set owned by a user. The bot will be able to edit the sticker set thus created. You must use exactly one of the fields _png\_sticker_ or _tgs\_sticker_. Returns _True_ on success. /// Use this method to create a new sticker set owned by a user. The bot will be able to edit the sticker set thus created. You must use exactly one of the fields _png\_sticker_ or _tgs\_sticker_. Returns _True_ on success.
@ -16,16 +16,15 @@ impl_payload! {
pub name: String [into], pub name: String [into],
/// Sticker set title, 1-64 characters /// Sticker set title, 1-64 characters
pub title: String [into], pub title: String [into],
/// **PNG** or **TGS** image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px. Pass a _file\_id_ as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. [More info on Sending Files »]
///
/// [More info on Sending Files »]: crate::types::InputFile
#[serde(flatten)]
pub sticker: InputSticker,
/// One or more emoji corresponding to the sticker /// One or more emoji corresponding to the sticker
pub emojis: String [into], pub emojis: String [into],
} }
optional { optional {
/// **PNG** image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px. Pass a _file\_id_ as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. [More info on Sending Files »]
///
/// [More info on Sending Files »]: crate::types::InputFile
pub png_sticker: InputFile,
/// **TGS** animation with the sticker, uploaded using multipart/form-data. See https://core.telegram.org/animated_stickers#technical-requirements for technical requirements
pub tgs_sticker: InputFile,
/// Pass _True_, if a set of mask stickers should be created /// Pass _True_, if a set of mask stickers should be created
pub contains_masks: bool, pub contains_masks: bool,
/// A JSON-serialized object for position where the mask should be placed on faces /// A JSON-serialized object for position where the mask should be placed on faces

View file

@ -3,14 +3,14 @@
// edit `cg` instead. // edit `cg` instead.
use serde::Serialize; use serde::Serialize;
use crate::types::User; use crate::types::Me;
impl_payload! { impl_payload! {
/// A simple method for testing your bot's auth token. Requires no parameters. Returns basic information about the bot in form of a [`User`] object. /// A simple method for testing your bot's auth token. Requires no parameters. Returns basic information about the bot in form of a [`User`] object.
/// ///
/// [`User`]: crate::types::User /// [`User`]: crate::types::User
#[derive(Debug, PartialEq, Eq, Hash, Default, Clone, Serialize)] #[derive(Debug, PartialEq, Eq, Hash, Default, Clone, Serialize)]
pub GetMe (GetMeSetters) => User { pub GetMe (GetMeSetters) => Me {
} }
} }

View file

@ -3,12 +3,12 @@
// edit `cg` instead. // edit `cg` instead.
use serde::Serialize; use serde::Serialize;
use crate::types::True; use crate::types::StickerSet;
impl_payload! { impl_payload! {
/// Use this method to get a sticker set. On success, a StickerSet object is returned. /// Use this method to get a sticker set. On success, a StickerSet object is returned.
#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize)] #[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize)]
pub GetStickerSet (GetStickerSetSetters) => True { pub GetStickerSet (GetStickerSetSetters) => StickerSet {
required { required {
/// Name of the sticker set /// Name of the sticker set
pub name: String [into], pub name: String [into],

View file

@ -44,7 +44,7 @@ pub trait Request: HasPayload {
/// use teloxide_core::{ /// use teloxide_core::{
/// payloads::GetMe, /// payloads::GetMe,
/// requests::{JsonRequest, Request}, /// requests::{JsonRequest, Request},
/// types::User, /// types::Me,
/// Bot, /// Bot,
/// }; /// };
/// ///
@ -53,7 +53,7 @@ pub trait Request: HasPayload {
/// // Note: it's recommended to `Requester` instead of creating requests directly /// // Note: it's recommended to `Requester` instead of creating requests directly
/// let method = GetMe::new(); /// let method = GetMe::new();
/// let request = JsonRequest::new(bot, method); /// let request = JsonRequest::new(bot, method);
/// let _: User = request.send().await.unwrap(); /// let _: Me = request.send().await.unwrap();
/// # }; /// # };
/// ``` /// ```
fn send(self) -> Self::Send; fn send(self) -> Self::Send;

View file

@ -617,6 +617,7 @@ pub trait Requester {
user_id: i32, user_id: i32,
name: N, name: N,
title: T, title: T,
sticker: InputSticker,
emojis: E, emojis: E,
) -> Self::CreateNewStickerSet ) -> Self::CreateNewStickerSet
where where

View file

@ -50,6 +50,7 @@ pub use inline_query_result_voice::*;
pub use input_file::*; pub use input_file::*;
pub use input_media::*; pub use input_media::*;
pub use input_message_content::*; pub use input_message_content::*;
pub use input_sticker::*;
pub use invoice::*; pub use invoice::*;
pub use keyboard_button::*; pub use keyboard_button::*;
pub use keyboard_button_poll_type::*; pub use keyboard_button_poll_type::*;
@ -80,7 +81,6 @@ pub use shipping_option::*;
pub use shipping_query::*; pub use shipping_query::*;
pub use sticker::*; pub use sticker::*;
pub use sticker_set::*; pub use sticker_set::*;
pub use sticker_type::*;
pub use successful_payment::*; pub use successful_payment::*;
pub use target_message::*; pub use target_message::*;
pub use unit_false::*; pub use unit_false::*;
@ -120,6 +120,7 @@ mod inline_keyboard_markup;
mod input_file; mod input_file;
mod input_media; mod input_media;
mod input_message_content; mod input_message_content;
mod input_sticker;
mod invoice; mod invoice;
mod keyboard_button; mod keyboard_button;
mod keyboard_button_poll_type; mod keyboard_button_poll_type;
@ -147,7 +148,6 @@ mod shipping_option;
mod shipping_query; mod shipping_query;
mod sticker; mod sticker;
mod sticker_set; mod sticker_set;
mod sticker_type;
mod successful_payment; mod successful_payment;
mod target_message; mod target_message;
mod unit_false; mod unit_false;

View file

@ -4,7 +4,6 @@ use crate::types::InputFile;
/// Sticker file that may be uploaded to telegram. /// Sticker file that may be uploaded to telegram.
#[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize)] #[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize)]
#[serde(untagged)]
pub enum InputSticker { pub enum InputSticker {
/// PNG image with the sticker, must be up to 512 kilobytes in size, /// PNG image with the sticker, must be up to 512 kilobytes in size,
/// dimensions must not exceed 512px, and either width or height must be /// dimensions must not exceed 512px, and either width or height must be
@ -20,30 +19,12 @@ pub enum InputSticker {
/// [`InputFile::FileId`]: crate::types::InputFile::FileId /// [`InputFile::FileId`]: crate::types::InputFile::FileId
/// ///
/// [More info on Sending Files »]: https://core.telegram.org/bots/api#sending-files /// [More info on Sending Files »]: https://core.telegram.org/bots/api#sending-files
Png { png_sticker: InputFile }, #[serde(rename = "png_sticker")]
Png(InputFile),
/// TGS animation with the sticker, uploaded using multipart/form-data. /// TGS animation with the sticker, uploaded using multipart/form-data.
/// ///
/// See https://core.telegram.org/animated_stickers#technical-requirements for technical requirements /// See https://core.telegram.org/animated_stickers#technical-requirements for technical requirements
Tgs { tgs_sticker: InputFile }, #[serde(rename = "tgs_sticker")]
} Tgs(InputFile),
impl InputSticker {
/// Create png-`InputSticker`.
///
/// See [`InputSticker::Png`] for more
///
/// [`InputSticker::Png`]: crate::types::InputSticker::Png
pub fn png(png_sticker: InputFile) -> Self {
Self::Png { png_sticker }
}
/// Create tgs-`InputSticker`.
///
/// See [`InputSticker::Tgs`] for more
///
/// [`InputSticker::Tgs`]: crate::types::InputSticker::Tgs
pub fn tgs(tgs_sticker: InputFile) -> Self {
Self::Tgs { tgs_sticker }
}
} }