https://github.com/Eloise1988/OPENAI/blob/main/asyncV2/README.md
api_id: Telegram API ID and Hash (you can get it from my.telegram.org) api_hash : Telegram API Hash (you can get it from my.telegram.org) session_hash : Telegram Session Hash (you can get it from my.telegram.org)
I found api_id and api_hash, but I didn't find session_hash
from telethon import TelegramClient
api_id = 123456 # Your API ID
api_hash = 'your_api_hash' # Your API Hash
# Create a new TelegramClient instance and start the client
async with TelegramClient('session_file', api_id, api_hash) as client:
# Connect to the Telegram servers and log in
await client.start()
# After logging in, the session hash will be automatically generated and stored
# in the 'session_file' file, which you can use in future runs to log in with
# the same session:
session_hash = client.session.save()
print(str(session_hash))
Related
I try to make a program to get the content of a Telegram Channel using Telethon (I'm begginer) :
from telethon import TelegramClient, events, sync
# Remember to use your own values from my.telegram.org!
api_id = 12345678
api_hash = "zdzhdzud"
client = TelegramClient(None, api_id, api_hash)
#client.on(events.NewMessage(chats='Channel_Test'))
async def my_event_handler(event):
print("\n\n\n",event.raw_text,"\n\n\n")
client.start()
client.run_until_disconnected()
I get "RuntimeWarning: Enable tracemalloc to get the object allocation traceback" 2 times.
Thank you
I expected to get a str for each message
After successful login from the consent screen, I am getting the access_token now the next step is to fetch all the view id from the google analytics account.Please help me out
Example: This is the access_token("ya29.A0ARrdaM8IvLg8jjVHWgxneSp_mxgFYHpKt4LwPGZEVqzOphMA2Cll6mjMxlQRFanbJHh1WrBEYVe2Y1BvBU6j7h_17nVeY4h-FWdUuv5bo0rzETTz_-xw4t5ZNBYpj26Cy3u4Y1trZnqVIA4")
You should check the Managment api quickstart python
"""A simple example of how to access the Google Analytics API."""
import argparse
from apiclient.discovery import build
import httplib2
from oauth2client import client
from oauth2client import file
from oauth2client import tools
def get_service(api_name, api_version, scope, client_secrets_path):
"""Get a service that communicates to a Google API.
Args:
api_name: string The name of the api to connect to.
api_version: string The api version to connect to.
scope: A list of strings representing the auth scopes to authorize for the
connection.
client_secrets_path: string A path to a valid client secrets file.
Returns:
A service that is connected to the specified API.
"""
# Parse command-line arguments.
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
parents=[tools.argparser])
flags = parser.parse_args([])
# Set up a Flow object to be used if we need to authenticate.
flow = client.flow_from_clientsecrets(
client_secrets_path, scope=scope,
message=tools.message_if_missing(client_secrets_path))
# Prepare credentials, and authorize HTTP object with them.
# If the credentials don't exist or are invalid run through the native client
# flow. The Storage object will ensure that if successful the good
# credentials will get written back to a file.
storage = file.Storage(api_name + '.dat')
credentials = storage.get()
if credentials is None or credentials.invalid:
credentials = tools.run_flow(flow, storage, flags)
http = credentials.authorize(http=httplib2.Http())
# Build the service object.
service = build(api_name, api_version, http=http)
return service
def get_first_profile_id(service):
# Use the Analytics service object to get the first profile id.
# Get a list of all Google Analytics accounts for the authorized user.
accounts = service.management().accounts().list().execute()
if accounts.get('items'):
# Get the first Google Analytics account.
account = accounts.get('items')[0].get('id')
# Get a list of all the properties for the first account.
properties = service.management().webproperties().list(
accountId=account).execute()
if properties.get('items'):
# Get the first property id.
property = properties.get('items')[0].get('id')
# Get a list of all views (profiles) for the first property.
profiles = service.management().profiles().list(
accountId=account,
webPropertyId=property).execute()
if profiles.get('items'):
# return the first view (profile) id.
return profiles.get('items')[0].get('id')
return None
def get_results(service, profile_id):
# Use the Analytics Service Object to query the Core Reporting API
# for the number of sessions in the past seven days.
return service.data().ga().get(
ids='ga:' + profile_id,
start_date='7daysAgo',
end_date='today',
metrics='ga:sessions').execute()
def print_results(results):
# Print data nicely for the user.
if results:
print 'View (Profile): %s' % results.get('profileInfo').get('profileName')
print 'Total Sessions: %s' % results.get('rows')[0][0]
else:
print 'No results found'
def main():
# Define the auth scopes to request.
scope = ['https://www.googleapis.com/auth/analytics.readonly']
# Authenticate and construct service.
service = get_service('analytics', 'v3', scope, 'client_secrets.json')
profile = get_first_profile_id(service)
print_results(get_results(service, profile))
if __name__ == '__main__':
main()
How do I forward a message to another chat as soon as I receive it from a contact?
I created this example just to test routing, but it doesn't work.
#!/usr/local/bin/python3
from telethon import TelegramClient, events
api_id = 9999900
api_hash = 'xxxxxxxxxxxxxxxxxxxxxxxxxxx'
client = TelegramClient('session_name', api_id, api_hash)
client.start()
#client.on(events.NewMessage)
async def main(event):
await client.send_message('Other People', 'Hello!') #Don't work. Keeps waiting forever
with client:
client.run_until_disconnected()
#client.on(events.NewMessage)
async def main(event):
await client.forward_messages(entity, event.message)
This code will work for forwarding new messages.
You can simply put chat_id of target user in place of entity
Is there any way to find a telegram channel id without sending a message to it ?
Right now I go this way and find the channel id by calling this URL in my code and get the JSON as result:
https://api.telegram.org/bot???????/sendMessage?chat_id=#?????&text=123
However, this cause sending the message "123" to the channel which is not good.
Check this link for help.
It is using web telegram url param info.
Adding details from the referred link:
log in web telegram
Click on the target channel then you will find the url displayed on your browser.
If it's a public channel, the ID is #name of the channel.
If it's a private channel then the url must be similar to:
https://web.telegram.org/#/im?p=c1018013852_555990343349619165
For this case, the channel ID would be 1018013852.
It's important to know that channel's IDs are always negative and 13 characters long!
So add -100 to it, making the correct ID -1001018013852.
You Can use Web Telegram to see each channel id in link of that page in your explorer
or
Just Simply Forward a message from your channel to This Bot: (https://telegram.me/getidsbot)
Yes, just forward a message of the channel to your bot and get the message.forward_from_chat.id.
Get your channel link
install python library telethon
get your api_id and api_hash here.
write the following code and run:
from telethon import TelegramClient
api_id=
api_hash=
channel_link = 'your_channel_link'
client = TelegramClient(session_name, api_id, api_hash,
update_workers=4, spawn_read_thread=False)
client.start()
entity = client.get_input_entity(**channel_link**)
print(entity.channel_id)
By the way, if you use it for telegram bot, just add -100 before the printed id, this should be work!
You Don't Need to get Channels ID .
simple send Message with Channel User Like : #channel
Fixing #scruel's answer:
In [1]: api_id = ...
In [2]: api_hash = '...'
In [3]: channelLink = 'https://t.me/BTCST_Community_EN'
In [4]: from telethon import TelegramClient, events
In [5]: client = TelegramClient('test', api_id, api_hash)
In [6]: client.start()
Out[6]: <telethon.client.telegramclient.TelegramClient at 0x7fc90c352290>
In [7]: entity = await client.get_entity(channelLink)
In [8]: channelId = '-100' + str(entity.id)
In [9]: channelId
Out[9]: '-1001236496320'
Here's a CLI util to do it:
#!env/bin/python
import sys
import asyncio
from telethon import TelegramClient
import config
async def channel_id_from_link(client, channel_link):
return "-100" + str((await client.get_entity(channel_link)).id)
async def main(channel_link):
async with TelegramClient(
"test", config.api_id, config.api_hash
) as client:
channel_id = await channel_id_from_link(client, channel_link)
return channel_id
if __name__ == "__main__":
channel_link = sys.argv[1]
channel_id = asyncio.run(main(channel_link))
print(channel_id)
Test:
> ./TelegramChannelId.py https://t.me/binance_api_english
-1001134190352
Put your bot into your channel and go to https://api.telegram.org/bot/getUpdates.
If someone send message to that channel, you will get the channel ID there.
I'm attempting to configure Flask-Security to send email asynchronously.
I have some code which send async email via Flask-Mail, but I'm having trouble integrating it with my application factory function so that it works in conjunction with Flask-Security.
Application factory:
mail = Mail()
db = SQLAlchemy()
security = Security()
from app.models import User, Role
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
def create_app(config_name):
# Config
app = Flask(__name__)
app.config.from_object(config[config_name])
config[config_name].init_app(app)
# Initialize extensions
mail.init_app(app)
db.init_app(app)
security.init_app(app, user_datastore)
return app
In the Flask-Security documentation it says to use #security.send_mail_task to override the way the extension sends emails.
So where exactly do I implement this decorator? Seems like anywhere I put it inside the application factory, I get circular imports.
These are the async email functions I am trying to use, taken from this issue:
#async
def send_security_email(msg):
with app.app_context():
mail.send(msg)
#security.send_mail_task
def async_security_email(msg):
send_security_email(msg)
Where does this code need to be put in order to work with the app factory?
Thanks in advance.
I was able to achieve this like so:
mail = Mail()
db = SQLAlchemy()
security = Security()
from app.models import User, Role
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
def create_app(config_name):
# Config
app = Flask(__name__)
app.config.from_object(config[config_name])
config[config_name].init_app(app)
# Initialize extensions
mail.init_app(app)
db.init_app(app)
security_ctx = security.init_app(app, user_datastore)
# Send Flask-Security emails asynchronously
#security_ctx.send_mail_task
def async_security_email(msg):
send_security_email(app, mail, msg)
return app