Merge branch 'develop' into asyncio

# Conflicts:
#	pyrogram/client/dispatcher/dispatcher.py
#	pyrogram/client/ext/utils.py
This commit is contained in:
Dan 2018-10-09 16:38:28 +02:00
commit e5f233b01e
17 changed files with 295 additions and 348 deletions

121
examples/LICENSE Normal file
View File

@ -0,0 +1,121 @@
Creative Commons Legal Code
CC0 1.0 Universal
CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
HEREUNDER.
Statement of Purpose
The laws of most jurisdictions throughout the world automatically confer
exclusive Copyright and Related Rights (defined below) upon the creator
and subsequent owner(s) (each and all, an "owner") of an original work of
authorship and/or a database (each, a "Work").
Certain owners wish to permanently relinquish those rights to a Work for
the purpose of contributing to a commons of creative, cultural and
scientific works ("Commons") that the public can reliably and without fear
of later claims of infringement build upon, modify, incorporate in other
works, reuse and redistribute as freely as possible in any form whatsoever
and for any purposes, including without limitation commercial purposes.
These owners may contribute to the Commons to promote the ideal of a free
culture and the further production of creative, cultural and scientific
works, or to gain reputation or greater distribution for their Work in
part through the use and efforts of others.
For these and/or other purposes and motivations, and without any
expectation of additional consideration or compensation, the person
associating CC0 with a Work (the "Affirmer"), to the extent that he or she
is an owner of Copyright and Related Rights in the Work, voluntarily
elects to apply CC0 to the Work and publicly distribute the Work under its
terms, with knowledge of his or her Copyright and Related Rights in the
Work and the meaning and intended legal effect of CC0 on those rights.
1. Copyright and Related Rights. A Work made available under CC0 may be
protected by copyright and related or neighboring rights ("Copyright and
Related Rights"). Copyright and Related Rights include, but are not
limited to, the following:
i. the right to reproduce, adapt, distribute, perform, display,
communicate, and translate a Work;
ii. moral rights retained by the original author(s) and/or performer(s);
iii. publicity and privacy rights pertaining to a person's image or
likeness depicted in a Work;
iv. rights protecting against unfair competition in regards to a Work,
subject to the limitations in paragraph 4(a), below;
v. rights protecting the extraction, dissemination, use and reuse of data
in a Work;
vi. database rights (such as those arising under Directive 96/9/EC of the
European Parliament and of the Council of 11 March 1996 on the legal
protection of databases, and under any national implementation
thereof, including any amended or successor version of such
directive); and
vii. other similar, equivalent or corresponding rights throughout the
world based on applicable law or treaty, and any national
implementations thereof.
2. Waiver. To the greatest extent permitted by, but not in contravention
of, applicable law, Affirmer hereby overtly, fully, permanently,
irrevocably and unconditionally waives, abandons, and surrenders all of
Affirmer's Copyright and Related Rights and associated claims and causes
of action, whether now known or unknown (including existing as well as
future claims and causes of action), in the Work (i) in all territories
worldwide, (ii) for the maximum duration provided by applicable law or
treaty (including future time extensions), (iii) in any current or future
medium and for any number of copies, and (iv) for any purpose whatsoever,
including without limitation commercial, advertising or promotional
purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
member of the public at large and to the detriment of Affirmer's heirs and
successors, fully intending that such Waiver shall not be subject to
revocation, rescission, cancellation, termination, or any other legal or
equitable action to disrupt the quiet enjoyment of the Work by the public
as contemplated by Affirmer's express Statement of Purpose.
3. Public License Fallback. Should any part of the Waiver for any reason
be judged legally invalid or ineffective under applicable law, then the
Waiver shall be preserved to the maximum extent permitted taking into
account Affirmer's express Statement of Purpose. In addition, to the
extent the Waiver is so judged Affirmer hereby grants to each affected
person a royalty-free, non transferable, non sublicensable, non exclusive,
irrevocable and unconditional license to exercise Affirmer's Copyright and
Related Rights in the Work (i) in all territories worldwide, (ii) for the
maximum duration provided by applicable law or treaty (including future
time extensions), (iii) in any current or future medium and for any number
of copies, and (iv) for any purpose whatsoever, including without
limitation commercial, advertising or promotional purposes (the
"License"). The License shall be deemed effective as of the date CC0 was
applied by Affirmer to the Work. Should any part of the License for any
reason be judged legally invalid or ineffective under applicable law, such
partial invalidity or ineffectiveness shall not invalidate the remainder
of the License, and in such case Affirmer hereby affirms that he or she
will not (i) exercise any of his or her remaining Copyright and Related
Rights in the Work or (ii) assert any associated claims and causes of
action with respect to the Work, in either case contrary to Affirmer's
express Statement of Purpose.
4. Limitations and Disclaimers.
a. No trademark or patent rights held by Affirmer are waived, abandoned,
surrendered, licensed or otherwise affected by this document.
b. Affirmer offers the Work as-is and makes no representations or
warranties of any kind concerning the Work, express, implied,
statutory or otherwise, including without limitation warranties of
title, merchantability, fitness for a particular purpose, non
infringement, or the absence of latent or other defects, accuracy, or
the present or absence of errors, whether or not discoverable, all to
the greatest extent permissible under applicable law.
c. Affirmer disclaims responsibility for clearing rights of other persons
that may apply to the Work or any use thereof, including without
limitation any person's Copyright and Related Rights in the Work.
Further, Affirmer disclaims responsibility for obtaining any necessary
consents, permissions or other rights required for any use of the
Work.
d. Affirmer understands and acknowledges that Creative Commons is not a
party to this document and has no duty or obligation with respect to
this CC0 or use of the Work.

View File

@ -5,14 +5,17 @@ This folder contains example scripts to show you how **Pyrogram** looks like.
Every script is working right away (provided you correctly set up your credentials), meaning Every script is working right away (provided you correctly set up your credentials), meaning
you can simply copy-paste and run. The only things you have to change are session names and target chats. you can simply copy-paste and run. The only things you have to change are session names and target chats.
All the examples listed in this directory are licensed under the terms of the [CC0 1.0 Universal](LICENSE) license and
can be freely used as basic building blocks for your own applications without worrying about copyrights.
Example | Description Example | Description
---: | :--- ---: | :---
[**hello_world**](hello_world.py) | Demonstration of basic API usages [**hello_world**](hello_world.py) | Demonstration of basic API usages
[**echo_bot**](echo_bot.py) | Echo bot that replies to every private text message [**echo_bot**](echo_bot.py) | Echo bot that replies to every private text message
[**welcome_bot**](welcome_bot.py) | The Welcome Bot source code in [@PyrogramChat](https://t.me/pyrogramchat) [**welcome_bot**](welcome_bot.py) | The Welcome Bot source code in [@PyrogramChat](https://t.me/pyrogramchat)
[**get_history**](get_history.py) | How to retrieve the full message history of a chat [**get_history**](get_history.py) | How to retrieve the full message history of a chat
[**get_participants**](get_participants.py) | How to get the first 10.000 members of a supergroup/channel [**get_chat_members**](get_chat_members.py) | How to get the first 10.000 members of a supergroup/channel
[**get_participants2**](get_participants2.py) | Improved version to get more than 10.000 users [**get_chat_members2**](get_chat_members2.py) | Improved version to get more than 10.000 members
[**query_inline_bots**](query_inline_bots.py) | How to query an inline bot and send a result to a chat [**query_inline_bots**](query_inline_bots.py) | How to query an inline bot and send a result to a chat
[**send_bot_keyboards**](send_bot_keyboards.py) | How to send normal and inline keyboards using regular bots [**send_bot_keyboards**](send_bot_keyboards.py) | How to send normal and inline keyboards using regular bots
[**callback_query_handler**](callback_query_handler.py) | How to handle queries coming from inline button presses [**callback_query_handler**](callback_query_handler.py) | How to handle queries coming from inline button presses

View File

@ -1,37 +1,16 @@
# Pyrogram - Telegram MTProto API Client Library for Python
# Copyright (C) 2017-2018 Dan Tès <https://github.com/delivrance>
#
# This file is part of Pyrogram.
#
# Pyrogram is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Pyrogram is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrogram. If not, see <http://www.gnu.org/licenses/>.
from pyrogram import Client
"""This example shows how to handle callback queries, i.e.: queries coming from inline button presses. """This example shows how to handle callback queries, i.e.: queries coming from inline button presses.
It uses the @on_callback_query decorator to register a CallbackQueryHandler.""" It uses the @on_callback_query decorator to register a CallbackQueryHandler.
"""
from pyrogram import Client
app = Client("123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11") app = Client("123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11")
@app.on_callback_query() @app.on_callback_query()
def answer(client, callback_query): def answer(client, callback_query):
client.answer_callback_query( callback_query.answer('Button contains: "{}"'.format(callback_query.data), show_alert=True)
callback_query.id,
text='Button contains: "{}"'.format(callback_query.data),
show_alert=True
)
app.run() # Automatically start() and idle() app.run() # Automatically start() and idle()

View File

@ -1,39 +1,17 @@
# Pyrogram - Telegram MTProto API Client Library for Python
# Copyright (C) 2017-2018 Dan Tès <https://github.com/delivrance>
#
# This file is part of Pyrogram.
#
# Pyrogram is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Pyrogram is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrogram. If not, see <http://www.gnu.org/licenses/>.
from pyrogram import Client, Filters
"""This simple echo bot replies to every private text message. """This simple echo bot replies to every private text message.
It uses the @on_message decorator to register a MessageHandler It uses the @on_message decorator to register a MessageHandler and applies two filters on it:
and applies two filters on it, Filters.text and Filters.private to make Filters.text and Filters.private to make sure it will reply to private text messages only.
sure it will only reply to private text messages.
""" """
from pyrogram import Client, Filters
app = Client("my_account") app = Client("my_account")
@app.on_message(Filters.text & Filters.private) @app.on_message(Filters.text & Filters.private)
def echo(client, message): def echo(client, message):
client.send_message( message.reply(message.text, quote=True)
message.chat.id, message.text,
reply_to_message_id=message.message_id
)
app.run() # Automatically start() and idle() app.run() # Automatically start() and idle()

View File

@ -0,0 +1,31 @@
"""This example shows you how to get the first 10.000 members of a chat.
Refer to get_chat_members2.py for more than 10.000 members.
"""
import time
from pyrogram import Client
from pyrogram.api.errors import FloodWait
app = Client("my_account")
target = "pyrogramchat" # Target channel/supergroup
members = [] # List that will contain all the members of the target chat
offset = 0 # Offset starts at 0
limit = 200 # Amount of users to retrieve for each API call (max 200)
with app:
while True:
try:
chunk = app.get_chat_members(target, offset)
except FloodWait as e: # Very large chats could trigger FloodWait
time.sleep(e.x) # When it happens, wait X seconds and try again
continue
if not chunk.chat_members:
break # No more members left
members.extend(chunk.chat_members)
offset += len(chunk.chat_members)
# Now the "members" list contains all the members of the target chat

View File

@ -0,0 +1,50 @@
"""This is an improved version of get_chat_members.py
Since Telegram will return at most 10.000 members for a single query, this script
repeats the search using numbers ("0" to "9") and all the available ascii letters ("a" to "z").
This can be further improved by also searching for non-ascii characters (e.g.: Japanese script),
as some user names may not contain ascii letters at all.
"""
import time
from string import ascii_lowercase
from pyrogram import Client
from pyrogram.api.errors import FloodWait
app = Client("my_account")
target = "pyrogramchat" # Target channel/supergroup
members = {} # List that will contain all the members of the target chat
limit = 200 # Amount of users to retrieve for each API call (max 200)
# "" + "0123456789" + "abcdefghijklmnopqrstuvwxyz" (as list)
queries = [""] + [str(i) for i in range(10)] + list(ascii_lowercase)
with app:
for q in queries:
print('Searching for "{}"'.format(q))
offset = 0 # For each query, offset restarts from 0
while True:
try:
chunk = app.get_chat_members(target, offset, query=q)
except FloodWait as e: # Very large chats could trigger FloodWait
print("Flood wait: {} seconds".format(e.x))
time.sleep(e.x) # When it happens, wait X seconds and try again
continue
if not chunk.chat_members:
print('Done searching for "{}"'.format(q))
print()
break # No more members left
members.update({i.user.id: i for i in chunk.chat_members})
offset += len(chunk.chat_members)
print("Total members: {}".format(len(members)))
print("Grand total: {}".format(len(members)))
# Now the "members" list contains all the members of the target chat

View File

@ -1,40 +1,20 @@
# Pyrogram - Telegram MTProto API Client Library for Python """This example shows how to retrieve the full message history of a chat"""
# Copyright (C) 2017-2018 Dan Tès <https://github.com/delivrance>
#
# This file is part of Pyrogram.
#
# Pyrogram is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Pyrogram is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrogram. If not, see <http://www.gnu.org/licenses/>.
import time import time
from pyrogram import Client from pyrogram import Client
from pyrogram.api.errors import FloodWait from pyrogram.api.errors import FloodWait
"""This example shows how to retrieve the full message history of a chat"""
app = Client("my_account") app = Client("my_account")
target = "me" # "me" refers to your own chat (Saved Messages) target = "me" # "me" refers to your own chat (Saved Messages)
messages = [] # List that will contain all the messages of the target chat messages = [] # List that will contain all the messages of the target chat
offset_id = 0 # ID of the last message of the chunk offset_id = 0 # ID of the last message of the chunk
app.start() with app:
while True:
while True:
try: try:
m = app.get_history(target, offset_id=offset_id) m = app.get_history(target, offset_id=offset_id)
except FloodWait as e: except FloodWait as e: # For very large chats the method call can raise a FloodWait
# For very large chats the method call can raise a FloodWait
print("waiting {}".format(e.x)) print("waiting {}".format(e.x))
time.sleep(e.x) # Sleep X seconds before continuing time.sleep(e.x) # Sleep X seconds before continuing
continue continue
@ -47,7 +27,5 @@ while True:
print("Messages: {}".format(len(messages))) print("Messages: {}".format(len(messages)))
app.stop()
# Now the "messages" list contains all the messages sorted by date in # Now the "messages" list contains all the messages sorted by date in
# descending order (from the most recent to the oldest one) # descending order (from the most recent to the oldest one)

View File

@ -1,63 +0,0 @@
# Pyrogram - Telegram MTProto API Client Library for Python
# Copyright (C) 2017-2018 Dan Tès <https://github.com/delivrance>
#
# This file is part of Pyrogram.
#
# Pyrogram is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Pyrogram is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrogram. If not, see <http://www.gnu.org/licenses/>.
import time
from pyrogram import Client
from pyrogram.api import functions, types
from pyrogram.api.errors import FloodWait
"""This simple GetParticipants method usage shows you how to get the first 10.000 users of a chat.
Refer to get_participants2.py for more than 10.000 users.
"""
app = Client("my_account")
target = "pyrogramchat" # Target channel/supergroup
users = [] # List that will contain all the users of the target chat
limit = 200 # Amount of users to retrieve for each API call
offset = 0 # Offset starts at 0
app.start()
while True:
try:
participants = app.send(
functions.channels.GetParticipants(
channel=app.resolve_peer(target),
filter=types.ChannelParticipantsSearch(""), # Filter by empty string (search for all)
offset=offset,
limit=limit,
hash=0
)
)
except FloodWait as e:
# Very large channels will trigger FloodWait.
# When happens, wait X seconds before continuing
time.sleep(e.x)
continue
if not participants.participants:
break # No more participants left
users.extend(participants.users)
offset += limit
app.stop()
# Now the "users" list contains all the members of the target chat

View File

@ -1,79 +0,0 @@
# Pyrogram - Telegram MTProto API Client Library for Python
# Copyright (C) 2017-2018 Dan Tès <https://github.com/delivrance>
#
# This file is part of Pyrogram.
#
# Pyrogram is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Pyrogram is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrogram. If not, see <http://www.gnu.org/licenses/>.
import time
from string import ascii_lowercase
from pyrogram import Client
from pyrogram.api import functions, types
from pyrogram.api.errors import FloodWait
"""This is an improved version of get_participants.py
Since Telegram will return at most 10.000 users for a single query, this script
repeats the search using numbers ("0" to "9") and all the available ascii letters ("a" to "z").
This can be further improved by also searching for non-ascii characters (e.g.: Japanese script),
as some user names may not contain ascii letters at all.
"""
app = Client("my_account")
target = "pyrogramchat" # Target channel/supergroup username or id
users = {} # To ensure uniqueness, users will be stored in a dictionary with user_id as key
limit = 200 # Amount of users to retrieve for each API call (200 is the maximum)
# "" + "0123456789" + "abcdefghijklmnopqrstuvwxyz" (as list)
queries = [""] + [str(i) for i in range(10)] + list(ascii_lowercase)
app.start()
for q in queries:
print("Searching for '{}'".format(q))
offset = 0 # For each query, offset restarts from 0
while True:
try:
participants = app.send(
functions.channels.GetParticipants(
channel=app.resolve_peer(target),
filter=types.ChannelParticipantsSearch(q),
offset=offset,
limit=limit,
hash=0
)
)
except FloodWait as e:
# Very large chats could trigger FloodWait.
# When happens, wait X seconds before continuing
print("Flood wait: {} seconds".format(e.x))
time.sleep(e.x)
continue
if not participants.participants:
print("Done searching for '{}'".format(q))
print()
break # No more participants left
# User information are stored in the participants.users list.
# Add those users to the dictionary
users.update({i.id: i for i in participants.users})
offset += len(participants.participants)
print("Total users: {}".format(len(users)))
app.stop()

View File

@ -1,25 +1,7 @@
# Pyrogram - Telegram MTProto API Client Library for Python """This example demonstrates a basic API usage"""
# Copyright (C) 2017-2018 Dan Tès <https://github.com/delivrance>
#
# This file is part of Pyrogram.
#
# Pyrogram is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Pyrogram is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrogram. If not, see <http://www.gnu.org/licenses/>.
from pyrogram import Client from pyrogram import Client
"""This example demonstrates a basic API usage"""
# Create a new Client instance # Create a new Client instance
app = Client("my_account") app = Client("my_account")

View File

@ -1,25 +1,7 @@
# Pyrogram - Telegram MTProto API Client Library for Python """This example shows how to query an inline bot"""
# Copyright (C) 2017-2018 Dan Tès <https://github.com/delivrance>
#
# This file is part of Pyrogram.
#
# Pyrogram is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Pyrogram is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrogram. If not, see <http://www.gnu.org/licenses/>.
from pyrogram import Client from pyrogram import Client
"""This example shows how to query an inline bot"""
# Create a new Client # Create a new Client
app = Client("my_account") app = Client("my_account")

View File

@ -1,25 +1,7 @@
# Pyrogram - Telegram MTProto API Client Library for Python """This example shows how to handle raw updates"""
# Copyright (C) 2017-2018 Dan Tès <https://github.com/delivrance>
#
# This file is part of Pyrogram.
#
# Pyrogram is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Pyrogram is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrogram. If not, see <http://www.gnu.org/licenses/>.
from pyrogram import Client from pyrogram import Client
"""This example shows how to handle raw updates"""
app = Client("my_account") app = Client("my_account")

View File

@ -1,23 +1,3 @@
# Pyrogram - Telegram MTProto API Client Library for Python
# Copyright (C) 2017-2018 Dan Tès <https://github.com/delivrance>
#
# This file is part of Pyrogram.
#
# Pyrogram is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Pyrogram is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrogram. If not, see <http://www.gnu.org/licenses/>.
from pyrogram import Client, ReplyKeyboardMarkup, InlineKeyboardMarkup, InlineKeyboardButton
"""This example will show you how to send normal and inline keyboards. """This example will show you how to send normal and inline keyboards.
You must log-in as a regular bot in order to send keyboards (use the token from @BotFather). You must log-in as a regular bot in order to send keyboards (use the token from @BotFather).
@ -27,6 +7,8 @@ send_message() is used as example, but a keyboard can be sent with any other sen
like send_audio(), send_document(), send_location(), etc... like send_audio(), send_document(), send_location(), etc...
""" """
from pyrogram import Client, ReplyKeyboardMarkup, InlineKeyboardMarkup, InlineKeyboardButton
# Create a client using your bot token # Create a client using your bot token
app = Client("123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11") app = Client("123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11")
app.start() app.start()

View File

@ -1,52 +1,27 @@
# Pyrogram - Telegram MTProto API Client Library for Python
# Copyright (C) 2017-2018 Dan Tès <https://github.com/delivrance>
#
# This file is part of Pyrogram.
#
# Pyrogram is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Pyrogram is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrogram. If not, see <http://www.gnu.org/licenses/>.
from pyrogram import Client, Emoji, Filters
"""This is the Welcome Bot in @PyrogramChat. """This is the Welcome Bot in @PyrogramChat.
It uses the Emoji module to easily add emojis in your text messages and Filters It uses the Emoji module to easily add emojis in your text messages and Filters
to make it only work for specific messages in a specific chat to make it only work for specific messages in a specific chat.
""" """
from pyrogram import Client, Emoji, Filters
MENTION = "[{}](tg://user?id={})"
MESSAGE = "{} Welcome to [Pyrogram](https://docs.pyrogram.ml/)'s group chat {}!"
app = Client("my_account") app = Client("my_account")
@app.on_message(Filters.chat("PyrogramChat") & Filters.new_chat_members) @app.on_message(Filters.chat("PyrogramChat") & Filters.new_chat_members)
def welcome(client, message): def welcome(client, message):
# Build the new members list (with mentions) by using their first_name # Build the new members list (with mentions) by using their first_name
new_members = ", ".join([ new_members = [MENTION.format(i.first_name, i.id) for i in message.new_chat_members]
"[{}](tg://user?id={})".format(i.first_name, i.id)
for i in message.new_chat_members
])
# Build the welcome message by using an emoji and the list we built above # Build the welcome message by using an emoji and the list we built above
text = "{} Welcome to [Pyrogram](https://docs.pyrogram.ml/)'s group chat {}!".format( text = MESSAGE.format(Emoji.SPARKLES, ", ".join(new_members))
Emoji.SPARKLES,
new_members
)
# Send the welcome message # Send the welcome message
client.send_message( message.reply(text, disable_web_page_preview=True)
message.chat.id, text,
reply_to_message_id=message.message_id,
disable_web_page_preview=True
)
app.run() # Automatically start() and idle() app.run() # Automatically start() and idle()

View File

@ -203,7 +203,7 @@ class Dispatcher:
await self.dispatch( await self.dispatch(
pyrogram.Update( pyrogram.Update(
callback_query=await utils.parse_inline_callback_query( callback_query=await utils.parse_inline_callback_query(
update, users self.client, update, users
) )
) )
) )

View File

@ -877,11 +877,12 @@ async def parse_callback_query(client, callback_query, users):
message=await client.get_messages(peer_id, callback_query.msg_id), message=await client.get_messages(peer_id, callback_query.msg_id),
chat_instance=str(callback_query.chat_instance), chat_instance=str(callback_query.chat_instance),
data=callback_query.data.decode(), data=callback_query.data.decode(),
game_short_name=callback_query.game_short_name game_short_name=callback_query.game_short_name,
client=client
) )
async def parse_inline_callback_query(callback_query, users): async def parse_inline_callback_query(client, callback_query, users):
return pyrogram_types.CallbackQuery( return pyrogram_types.CallbackQuery(
id=str(callback_query.query_id), id=str(callback_query.query_id),
from_user=parse_user(users[callback_query.user_id]), from_user=parse_user(users[callback_query.user_id]),
@ -895,7 +896,8 @@ async def parse_inline_callback_query(callback_query, users):
), ),
b"-_" b"-_"
).decode().rstrip("="), ).decode().rstrip("="),
game_short_name=callback_query.game_short_name game_short_name=callback_query.game_short_name,
client=client
) )

View File

@ -57,11 +57,13 @@ class CallbackQuery(Object):
id: str, id: str,
from_user, from_user,
chat_instance: str, chat_instance: str,
client=None,
message=None, message=None,
inline_message_id: str = None, inline_message_id: str = None,
data: str = None, data: str = None,
game_short_name: str = None game_short_name: str = None
): ):
self._client = client
self.id = id # string self.id = id # string
self.from_user = from_user # User self.from_user = from_user # User
self.message = message # flags.0?Message self.message = message # flags.0?Message
@ -69,3 +71,45 @@ class CallbackQuery(Object):
self.chat_instance = chat_instance # string self.chat_instance = chat_instance # string
self.data = data # flags.2?string self.data = data # flags.2?string
self.game_short_name = game_short_name # flags.3?string self.game_short_name = game_short_name # flags.3?string
def answer(self, text: str = None, show_alert: bool = None, url: str = None, cache_time: int = 0):
"""Use this method as a shortcut for:
.. code-block:: python
client.answer_callback_query(
callback_query.id,
text="Hello",
show_alert=True
)
Example:
.. code-block:: python
callback_query.answer("Hello", show_alert=True)
Args:
text (``str``):
Text of the notification. If not specified, nothing will be shown to the user, 0-200 characters.
show_alert (``bool``):
If true, an alert will be shown by the client instead of a notification at the top of the chat screen.
Defaults to False.
url (``str``):
URL that will be opened by the user's client.
If you have created a Game and accepted the conditions via @Botfather, specify the URL that opens your
game note that this will only work if the query comes from a callback_game button.
Otherwise, you may use links like t.me/your_bot?start=XXXX that open your bot with a parameter.
cache_time (``int``):
The maximum amount of time in seconds that the result of the callback query may be cached client-side.
Telegram apps will support caching starting in version 3.14. Defaults to 0.
"""
return self._client.answer_callback_query(
callback_query_id=self.id,
text=text,
show_alert=show_alert,
url=url,
cache_time=cache_time
)