本文整理汇总了Python中telethon.TelegramClient方法的典型用法代码示例。如果您正苦于以下问题:Python telethon.TelegramClient方法的具体用法?Python telethon.TelegramClient怎么用?Python telethon.TelegramClient使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类telethon
的用法示例。
在下文中一共展示了telethon.TelegramClient方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: import telethon [as 别名]
# 或者: from telethon import TelegramClient [as 别名]
def main(loop, interval=0.05):
client = TelegramClient(SESSION, API_ID, API_HASH, loop=loop)
try:
await client.connect()
except Exception as e:
print('Failed to connect', e, file=sys.stderr)
return
app = App(client)
try:
while True:
# We want to update the application but get back
# to asyncio's event loop. For this we sleep a
# short time so the event loop can run.
#
# https://www.reddit.com/r/Python/comments/33ecpl
app.update()
await asyncio.sleep(interval)
except KeyboardInterrupt:
pass
except tkinter.TclError as e:
if 'application has been destroyed' not in e.args[0]:
raise
finally:
await app.cl.disconnect()
示例2: list_event_handlers
# 需要导入模块: import telethon [as 别名]
# 或者: from telethon import TelegramClient [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]
示例3: _process_update
# 需要导入模块: import telethon [as 别名]
# 或者: from telethon import TelegramClient [as 别名]
def _process_update(self: 'TelegramClient', update, others, entities=None):
update._entities = entities or {}
# This part is somewhat hot so we don't bother patching
# update with channel ID/its state. Instead we just pass
# arguments which is faster.
channel_id = self._state_cache.get_channel_id(update)
args = (update, others, channel_id, self._state_cache[channel_id])
if self._dispatching_updates_queue is None:
task = self._loop.create_task(self._dispatch_update(*args))
self._updates_queue.add(task)
task.add_done_callback(lambda _: self._updates_queue.discard(task))
else:
self._updates_queue.put_nowait(args)
if not self._dispatching_updates_queue.is_set():
self._dispatching_updates_queue.set()
self._loop.create_task(self._dispatch_queue_updates())
self._state_cache.update(update)
示例4: setUpClass
# 需要导入模块: import telethon [as 别名]
# 或者: from telethon import TelegramClient [as 别名]
def setUpClass(cls):
cls.dumper_config = {'DBFileName': 'test_db', 'OutputDirectory': 'test_work_dir',
'MaxSize': 0}
# TODO test with different configurations
assert not Path(cls.dumper_config['OutputDirectory']).exists()
Path(cls.dumper_config['OutputDirectory']).mkdir()
config = configparser.ConfigParser()
config.read('config.ini')
config = config['TelegramAPI']
cls.client = TelegramClient(None, config['ApiId'], config['ApiHash'])
login_client(cls.client, gen_username(10))
dumper = Dumper(cls.dumper_config)
dumper.check_self_user(cls.client.get_me().id)
示例5: download_file
# 需要导入模块: import telethon [as 别名]
# 或者: from telethon import TelegramClient [as 别名]
def download_file(
self: TelegramClient, location: TypeLocation,
out: BinaryIO, progress_callback: callable = None
) -> BinaryIO:
size = location.size
dc_id, location = utils.get_input_location(location)
# We lock the transfers because telegram has connection count limits
downloader = ParallelTransferrer(self, dc_id)
downloaded = downloader.download(location, size)
async for x in downloaded:
out.write(x)
if progress_callback:
r = progress_callback(out.tell(), size)
if inspect.isawaitable(r):
await r
return out
示例6: init_client
# 需要导入模块: import telethon [as 别名]
# 或者: from telethon import TelegramClient [as 别名]
def init_client(self: "Bot") -> None:
# Get Telegram parameters from config and check types
session_name = self.tg_config["session_name"]
if not isinstance(session_name, str):
raise TypeError("Session name must be a string")
api_id = self.tg_config["api_id"]
if not isinstance(api_id, int):
raise TypeError("API ID must be an integer")
api_hash = self.tg_config["api_hash"]
if not isinstance(api_hash, str):
raise TypeError("API hash must be a string")
# Initialize Telegram client with gathered parameters
self.client = tg.TelegramClient(
session_name, api_id, api_hash, connection_retries=10, retry_delay=5
)
示例7: upload_file
# 需要导入模块: import telethon [as 别名]
# 或者: from telethon import TelegramClient [as 别名]
def upload_file(
self: TelegramClient, file: BinaryIO, progress_callback: callable = None
) -> TypeInputFile:
res = (
await _internal_transfer_to_telegram(self, file, progress_callback)
)[0]
return res
示例8: download_file
# 需要导入模块: import telethon [as 别名]
# 或者: from telethon import TelegramClient [as 别名]
def download_file(self: TelegramClient,
location: TypeLocation,
out: BinaryIO,
progress_callback: callable = None) -> BinaryIO:
size = location.size
dc_id, location = utils.get_input_location(location)
# We lock the transfers because telegram has connection count limits
downloader = ParallelTransferrer(self, dc_id)
downloaded = downloader.download(location, size)
async for x in downloaded:
out.write(x)
if progress_callback:
r = progress_callback(out.tell(), size)
if inspect.isawaitable(r):
await r
return out
示例9: send_tg_code
# 需要导入模块: import telethon [as 别名]
# 或者: from telethon import TelegramClient [as 别名]
def send_tg_code(self, request):
if self.client_data and await self.check_user(request) is None:
return web.Response(status=302, headers={"Location": "/"}) # They gotta sign in.
text = await request.text()
phone = telethon.utils.parse_phone(text)
if not phone:
return web.Response(status=400)
client = telethon.TelegramClient(telethon.sessions.MemorySession(), self.api_token.ID,
self.api_token.HASH, connection_retries=None)
await client.connect()
await client.send_code_request(phone)
self.sign_in_clients[phone] = client
return web.Response()
示例10: _dispatch_queue_updates
# 需要导入模块: import telethon [as 别名]
# 或者: from telethon import TelegramClient [as 别名]
def _dispatch_queue_updates(self: 'TelegramClient'):
while not self._updates_queue.empty():
await self._dispatch_update(*self._updates_queue.get_nowait())
self._dispatching_updates_queue.clear()
示例11: __init__
# 需要导入模块: import telethon [as 别名]
# 或者: from telethon import TelegramClient [as 别名]
def __init__(self, client: 'TelegramClient', update, others):
self.client = client
self.update = update
self.others = others
示例12: test_all_methods_present
# 需要导入模块: import telethon [as 别名]
# 或者: from telethon import TelegramClient [as 别名]
def test_all_methods_present(docs_dir):
with (docs_dir / 'quick-references/client-reference.rst').open(encoding='utf-8') as fd:
present_methods = set(map(str.lstrip, re.findall(r'^ {4}\w+$', fd.read(), re.MULTILINE)))
assert len(present_methods) > 0
for name in dir(TelegramClient):
attr = getattr(TelegramClient, name)
if callable(attr) and not name.startswith('_'):
assert name in present_methods
示例13: get_client
# 需要导入模块: import telethon [as 别名]
# 或者: from telethon import TelegramClient [as 别名]
def get_client():
return TelegramClient(None, 1, '1')
示例14: main
# 需要导入模块: import telethon [as 别名]
# 或者: from telethon import TelegramClient [as 别名]
def main():
load_config()
proxy = config.get('proxy', {})
if proxy:
import socks
proxy = (socks.SOCKS5, proxy.get('address'), proxy.get('port'))
bot = TelegramClient('bot', config['api_id'], config['api_hash'], proxy=proxy, connection_retries=0)
else:
bot = TelegramClient('bot', config['api_id'], config['api_hash'], connection_retries=0)
bot.add_event_handler(challenge_user)
bot.add_event_handler(handle_challenge_response)
wait_time = 1
while True:
start_time = time.time()
try:
await bot.start(bot_token=config['token'])
await bot.run_until_disconnected()
except ConnectionError:
if time.time()-start_time < 2:
wait_time = min(wait_time*2, 256)
else:
wait_time = 1
logging.info(f'Reconnect after {wait_time} seconds...')
time.sleep(wait_time)
continue
示例15: run_telethon
# 需要导入模块: import telethon [as 别名]
# 或者: from telethon import TelegramClient [as 别名]
def run_telethon(self):
if self.proc:
self.proc.disconnect()
self.proc = TelegramClient(options.tg_session, options.tg_api_id, options.tg_api_hash)
try:
self.proc.connect()
except:
error('Failed to connect to Telegram server')
sys.exit(2)
self.authorized = self.proc.is_user_authorized()
if not self.authorized and not options.tg_phone:
error('Not authorized. Please set --tg-phone')
sys.exit(2)
self.proc.add_event_handler(server.on_telegram_update)