如何解决如何使用Telethon连接到Telegram?
也许这是一个经常性的话题,但是我看了一下,发现下面的列表没有解决我的问题:
- Singing in TelegramClient telethon
- When starting client the code is asking for phone/bot token
- Hosting a Telethon User BOT on google-app-engine
- How to search for groups and channel in telegram using telethon?
到目前为止,这些解决方案都没有帮助我。
- 我不在Telegram上使用2FA
我的代码如下
import configparser
import json
import asyncio
import nest_asyncio
from datetime import date,datetime
from telethon import TelegramClient,sync,functions
from telethon.errors import SessionPasswordNeededError
from telethon.tl.functions.messages import (GetHistoryRequest)
from telethon.tl.functions.contacts import ResolveUsernameRequest
from telethon.tl.types import (PeerChannel)
nest_asyncio.apply()
# some functions to parse json date
class DateTimeEncoder(json.JSONEncoder):
def default(self,o):
if isinstance(o,datetime):
return o.isoformat()
if isinstance(o,bytes):
return list(o)
return json.JSONEncoder.default(self,o)
class MyBot:
api_id = None
api_hash = None
phone = None
username = None
channel = None
debug = "False"
client = None
loaded = "False"
def readConfig (self):
config = configparser.ConfigParser()
config.read("config.ini")
# Setting configuration values
self.api_id = config['Telegram']['api_id']
self.api_hash = config['Telegram']['api_hash']
self.api_hash = str(self.api_hash)
self.phone = config['Telegram']['phone']
self.username = config['Telegram']['username']
self.channel = config['Telegram']['channel']
self.debug = config['Telegram']['debug']
if self.api_id != None:
if self.api_hash != None:
if self.phone != None:
if self.username != None:
if self.channel != None:
self.loaded = "True"
def printConfig (self):
if self.debug == "True":
print("api_id: "+self.api_id)
print("api_hash: "+self.api_hash)
print("phone: "+self.phone)
print("username: "+self.username)
else: print("Debug if False")
async def createClient(self):
if self.loaded == "True":
print("Creating Client")
client = TelegramClient(session="session",api_id =self.api_id,api_hash =self.api_hash)
await client.start()
# Ensure you're authorized
if not await client.is_user_authorized():
await client.send_code_request(self.phone)
try:
await client.sign_in(self.phone,input('Enter the code: '))
except SessionPasswordNeededError:
await client.sign_in(password=input('Password: '))
search = 'linux'
result = await client(functions.contacts.SearchRequest(
q=search,limit=100
))
print(result.stringify())
myBot = MyBot()
myBot .readConfig()
myBot .printConfig()
#myBot .createClient()
asyncio.ensure_future(myBot .createClient())
在与此代码相同的文件夹中,我还有一个config.ini文件,其中包含用于我的凭据的通用设置,以便使用Telegram API。
当我运行这段代码时,它会返回
- api_id:1234567(此处为假值)
- api_hash:xyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxy
- 电话:+
- 用户名:@myIdonTelegram
- 创建客户
- 请输入您的电话(或漫游器令牌):
我无法逃脱此提示询问我的电话,即使我键入它也没有任何反应 我想念什么?为什么让我问我的电话以及如何通过电话?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。