本文整理汇总了Python中telethon.events.NewMessage方法的典型用法代码示例。如果您正苦于以下问题:Python events.NewMessage方法的具体用法?Python events.NewMessage怎么用?Python events.NewMessage使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类telethon.events
的用法示例。
在下文中一共展示了events.NewMessage方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: list_event_handlers
# 需要导入模块: from telethon import events [as 别名]
# 或者: from telethon.events import NewMessage [as 别名]
def list_event_handlers(self: 'TelegramClient')\
-> 'typing.Sequence[typing.Tuple[callable, EventBuilder]]':
"""
Lists all registered event handlers.
Returns
A list of pairs consisting of ``(callback, event)``.
Example
.. code-block:: python
@client.on(events.NewMessage(pattern='hello'))
async def on_greeting(event):
'''Greets someone'''
await event.reply('Hi')
for callback, event in client.list_event_handlers():
print(id(callback), type(event))
"""
return [(callback, event) for event, callback in self._event_builders]
示例2: can_react
# 需要导入模块: from telethon import events [as 别名]
# 或者: from telethon.events import NewMessage [as 别名]
def can_react(chat_id):
# Get the time when we last sent a reaction (or 0)
last = recent_reacts[chat_id]
# Get the current time
now = time.time()
# If 10 minutes as seconds have passed, we can react
if now - last < 10 * 60:
# Make sure we updated the last reaction time
recent_reacts[chat_id] = now
return True
else:
return False
# Register `events.NewMessage` before defining the client.
# Once you have a client, `add_event_handler` will use this event.
示例3: create_token_file
# 需要导入模块: from telethon import events [as 别名]
# 或者: from telethon.events import NewMessage [as 别名]
def create_token_file(token_file, event):
# Run through the OAuth flow and retrieve credentials
flow = OAuth2WebServerFlow(
CLIENT_ID,
CLIENT_SECRET,
OAUTH_SCOPE,
redirect_uri=REDIRECT_URI
)
authorize_url = flow.step1_get_authorize_url()
async with event.client.conversation(Config.PRIVATE_GROUP_BOT_API_ID) as conv:
await conv.send_message(f"Go to the following link in your browser: {authorize_url} and reply the code")
response = conv.wait_event(events.NewMessage(
outgoing=True,
chats=Config.PRIVATE_GROUP_BOT_API_ID
))
response = await response
code = response.message.message.strip()
credentials = flow.step2_exchange(code)
storage = Storage(token_file)
storage.put(credentials)
return storage
示例4: translator
# 需要导入模块: from telethon import events [as 别名]
# 或者: from telethon.events import NewMessage [as 别名]
def translator(event: events.NewMessage.Event):
global draft_semaphore
await draft_semaphore.acquire()
try:
draft_list = await client.get_drafts()
for draft in draft_list:
if draft.is_empty:
continue
text = draft.text
for lang_code in supported_langs.values():
if text.endswith('/{0}'.format(lang_code)):
translated = mtranslate.translate(text[:-(len(lang_code) + 1)], lang_code, 'auto')
for i in range(3):
try:
await draft.set_message(text=translated)
await asyncio.sleep(7)
return
except Exception as e:
print(e)
except Exception as e:
print(e)
finally:
draft_semaphore.release()
示例5: on
# 需要导入模块: from telethon import events [as 别名]
# 或者: from telethon.events import NewMessage [as 别名]
def on(self: 'TelegramClient', event: EventBuilder):
"""
Decorator used to `add_event_handler` more conveniently.
Arguments
event (`_EventBuilder` | `type`):
The event builder class or instance to be used,
for instance ``events.NewMessage``.
Example
.. code-block:: python
from telethon import TelegramClient, events
client = TelegramClient(...)
# Here we use client.on
@client.on(events.NewMessage)
async def handler(event):
...
"""
def decorator(f):
self.add_event_handler(f, event)
return f
return decorator
示例6: remove_event_handler
# 需要导入模块: from telethon import events [as 别名]
# 或者: from telethon.events import NewMessage [as 别名]
def remove_event_handler(
self: 'TelegramClient',
callback: callable,
event: EventBuilder = None) -> int:
"""
Inverse operation of `add_event_handler()`.
If no event is given, all events for this callback are removed.
Returns how many callbacks were removed.
Example
.. code-block:: python
@client.on(events.Raw)
@client.on(events.NewMessage)
async def handler(event):
...
# Removes only the "Raw" handling
# "handler" will still receive "events.NewMessage"
client.remove_event_handler(handler, events.Raw)
# "handler" will stop receiving anything
client.remove_event_handler(handler)
"""
found = 0
if event and not isinstance(event, type):
event = type(event)
i = len(self._event_builders)
while i:
i -= 1
ev, cb = self._event_builders[i]
if cb == callback and (not event or isinstance(ev, event)):
del self._event_builders[i]
found += 1
return found
示例7: start_handler
# 需要导入模块: from telethon import events [as 别名]
# 或者: from telethon.events import NewMessage [as 别名]
def start_handler(event: events.NewMessage.Event):
await bot.send_message(
event.chat_id, 'Sending invoice A',
file=generate_invoice(
price_label='Pay', price_amount=10000, currency='RUB', title='Title A', description='description A',
payload='product A', start_param='abc'
)
)
示例8: handler
# 需要导入模块: from telethon import events [as 别名]
# 或者: from telethon.events import NewMessage [as 别名]
def handler(event):
await event.delete()
text = 'Available commands:\n'
for callback, handler in bot.list_event_handlers():
if isinstance(handler, events.NewMessage) and callback.__doc__:
text += f'\n{callback.__doc__.strip()}'
text += '\n\nYou can suggest new commands [here](https://docs.google.com/'\
'spreadsheets/d/12yWwixUu_vB426_toLBAiajXxYKvR2J1DD6yZtQz9l4/edit).'
message = await event.respond(text, link_preview=False)
await asyncio.sleep(1 * text.count(' ')) # Sleep ~1 second per word
await message.delete()
示例9: message_handler
# 需要导入模块: from telethon import events [as 别名]
# 或者: from telethon.events import NewMessage [as 别名]
def message_handler(self, event):
"""Callback method for received events.NewMessage"""
# Note that message_handler is called when a Telegram update occurs
# and an event is created. Telegram may not always send information
# about the ``.sender`` or the ``.chat``, so if you *really* want it
# you should use ``get_chat()`` and ``get_sender()`` while working
# with events. Since they are methods, you know they may make an API
# call, which can be expensive.
chat = await event.get_chat()
if event.is_group:
if event.out:
sprint('>> sent "{}" to chat {}'.format(
event.text, get_display_name(chat)
))
else:
sprint('<< {} @ {} sent "{}"'.format(
get_display_name(await event.get_sender()),
get_display_name(chat),
event.text
))
else:
if event.out:
sprint('>> "{}" to user {}'.format(
event.text, get_display_name(chat)
))
else:
sprint('<< {} sent "{}"'.format(
get_display_name(chat), event.text
))
示例10: start
# 需要导入模块: from telethon import events [as 别名]
# 或者: from telethon.events import NewMessage [as 别名]
def start(event):
"""Send a message when the command /start is sent."""
# sender_info = await get_user_info(event)
# DATABASE.add_chat_to_db(sender_info)
locale = DATABASE.get_locale(event.chat_id)
if not event.is_private:
message, buttons = await welcome_in_pm_message(locale)
try:
await event.reply(message, buttons=buttons)
except ChatWriteForbiddenError:
pass
return
try:
key = event.message.message.split('/start ')[1]
except IndexError:
key = None
if event.message.message.endswith('help'):
await show_help(event)
elif key and key != 'start':
try:
decoded = b64decode(key).decode()
if "/subscribe" in decoded:
event.message.message = decoded
await subscribe(event)
except UnicodeDecodeError:
pass
else:
message, buttons = await welcome_message(locale)
try:
await event.reply(message, buttons=buttons, link_preview=False)
except UserIsBlockedError:
pass
raise events.StopPropagation # Other handlers won't have an event to work with
# @BOT.on(events.NewMessage)
# async def echo(event):
# """Echo the user message."""
# await event.respond(event.text)
# # await event.respond('A single button, with "clk1" as data',
# # buttons=Button.inline('Click me', b'clk1'))
示例11: _
# 需要导入模块: from telethon import events [as 别名]
# 或者: from telethon.events import NewMessage [as 别名]
def _(event):
if event.fwd_from:
return
if not event.reply_to_msg_id:
await event.edit("```Reply to any user message.```")
return
reply_message = await event.get_reply_message()
if not reply_message.text:
await event.edit("```Reply to text message```")
return
chat = "@QuotLyBot"
sender = reply_message.sender
if reply_message.sender.bot:
await event.edit("```Reply to actual users message.```")
return
await event.edit("```Making a Quote```")
async with event.client.conversation(chat) as conv:
try:
response = conv.wait_event(events.NewMessage(incoming=True,from_users=1031952739))
await event.client.forward_messages(chat, reply_message)
response = await response
except YouBlockedUserError:
await event.reply("```Please unblock me (@QuotLyBot) u Nigga```")
return
if response.text.startswith("Hi!"):
await event.edit("```Can you kindly disable your forward privacy settings for good?```")
else:
await event.delete()
await event.client.send_message(event.chat_id, response.message)
示例12: choser
# 需要导入模块: from telethon import events [as 别名]
# 或者: from telethon.events import NewMessage [as 别名]
def choser(cmd, pack, blacklist={}):
docs = None
@borg.on(events.NewMessage(pattern=rf'\.{cmd}', outgoing=True))
async def handler(event):
await event.delete()
nonlocal docs
if docs is None:
docs = [
utils.get_input_document(x)
for x in (await borg(functions.messages.GetStickerSetRequest(types.InputStickerSetShortName(pack)))).documents
if x.id not in blacklist
]
await event.respond(file=random.choice(docs))
示例13: _
# 需要导入模块: from telethon import events [as 别名]
# 或者: from telethon.events import NewMessage [as 别名]
def _(event):
if event.fwd_from:
return
if not event.reply_to_msg_id:
await event.edit("```Reply to any user message.```")
return
reply_message = await event.get_reply_message()
if not reply_message.text:
await event.edit("```reply to text message```")
return
chat = "@SangMataInfo_bot"
sender = reply_message.sender
if reply_message.sender.bot:
await event.edit("```Reply to actual users message.```")
return
await event.edit("```Processing```")
async with borg.conversation(chat) as conv:
try:
response = conv.wait_event(events.NewMessage(incoming=True,from_users=461843263))
await borg.forward_messages(chat, reply_message)
response = await response
except YouBlockedUserError:
await event.reply("```Please unblock @sangmatainfo_bot and try again```")
return
if response.text.startswith("Forward"):
await event.edit("```can you kindly disable your forward privacy settings for good?```")
else:
await event.edit(f"{response.message.message}")
示例14: _
# 需要导入模块: from telethon import events [as 别名]
# 或者: from telethon.events import NewMessage [as 别名]
def _(event):
if event.fwd_from:
return
if not event.reply_to_msg_id:
await event.edit("```Reply to any user message.```")
return
reply_message = await event.get_reply_message()
if not reply_message.media:
await event.edit("```reply to text message```")
return
chat = "@image_deepfrybot"
sender = reply_message.sender
if reply_message.sender.bot:
await event.edit("```Reply to actual users message.```")
return
await event.edit("```Processing```")
async with borg.conversation(chat) as conv:
try:
response = conv.wait_event(events.NewMessage(incoming=True,from_users=432858024))
await borg.send_message(chat, reply_message)
response = await response
except YouBlockedUserError:
await event.reply("```Please unblock @sangmatainfo_bot and try again```")
return
if response.text.startswith("Forward"):
await event.edit("```can you kindly disable your forward privacy settings for good?```")
else:
await borg.send_file(event.chat_id, response.message.media)
示例15: _
# 需要导入模块: from telethon import events [as 别名]
# 或者: from telethon.events import NewMessage [as 别名]
def _(event):
if event.fwd_from:
return
if not event.reply_to_msg_id:
await event.edit("```Reply to any user message.```")
return
reply_message = await event.get_reply_message()
if not reply_message.media:
await event.edit("```reply to a media message```")
return
chat = "@DrWebBot"
sender = reply_message.sender
if reply_message.sender.bot:
await event.edit("```Reply to actual users message.```")
return
await event.edit(" **covid19 will end with the end of April-2020 from the globe.** `still let me check this thing.`")
async with borg.conversation(chat) as conv:
try:
response = conv.wait_event(events.NewMessage(incoming=True,from_users=161163358))
await borg.forward_messages(chat, reply_message)
response = await response
except YouBlockedUserError:
await event.reply("```Please unblock @sangmatainfo_bot and try again```")
return
if response.text.startswith("Forward"):
await event.edit("```can you kindly disable your forward privacy settings for good?```")
else:
if response.text.startswith("Select"):
await event.edit("`Please go to` @DrWebBot `and select your language.`")
else:
await event.edit(f"`Antivirus scan was completed.`\n**covid19 will end with the end of April-2020 from the globe.**\n`YAH, I got dem final results.`\n {response.message.message}")