SORRY FOR MY ENGLISH!))
Trying to launch telegram client on pythonanywhere hosting using flask
Loaded all necessary libraries (see photo1)
On this site created an api-application, got it app_id and api_hash
Further, I made a flask application with this code (for test)
#app.route('/')
def hello_world():
#------------------------If an error occurred during import------------
try:
from telethon import TelegramClient, sync
except Exception as e:
return 'IMPORT ERROR: ' + str(e)
#------------------------we catch it-----------------------------------
api_id = API_ID_FROM_MY_TELEGRAM_ORG #Тут подставляю свое
api_hash = API_HASH_CODE_FROM_MY_TELEGRAM_ORG #Тут подставляю свое
#----------If an error occurred while creating the object--------------
try:
client = TelegramClient('test_session', api_id, api_hash)
return 'Succes!'
except Exception as e:
return 'OBJECT ERROR: ' + str(e)
#------------------------we catch it-----------------------------------
When you start and open the application in the browser, the following error is displayed (in text form):
OBJECT ERROR: database is locked
This text corresponds to the last try/catch construction, so an error occurs when trying to create an object client = TelegramClient('test_session', api_id, api_hash)
What is this exception and how in my case to fight it?
Related
I wrote a script for the documentation of pyrogram for parsing messages in public chats, but it either gives me an error, or does not give anything at all, here is the code:
from pyrogram import Client
api_id = 272347
api_hash = '235ausfhi...'
gruppa = 'xxx'
with Client('sessia1', api_id, api_hash) as app:
spis_mas = []
for message in app.iter_history(gruppa):
spis_mas.append(message.text)
with open('spis_of_mes.txt', 'w') as file:
for mem in spis_mas:
file.write(str(mem) + '\n')
Here is the error:
[sessia1] Sleeping for 26s (required by "channels.GetMessages")
That is not an Error -
You cant get a all history with iter_history in one time
you should wait to iter_history generator finish !
I am trying simple thing, add local picture to my slack channel using python script. I have not found the answer. I have created slack app for my channel and have Verification Token and APP ID.
I have tried following with no result:
import requests
files = {
'file': ('dog.jpg', open('dog.jpg', 'rb')),
'channels': (None, 'App ID,#channel'),
'token': (None, 'Verification Token'),
}
And:
import os
from slack import WebClient
from slack.errors import SlackApiError
client = WebClient(token=os.environ['SLACK_API_TOKEN'])
try:
filepath="./tmp.txt"
response = client.files_upload(
channels='#random',
file=filepath)
assert response["file"] # the uploaded file
except SlackApiError as e:
# You will get a SlackApiError if "ok" is False
assert e.response["ok"] is False
assert e.response["error"] # str like 'invalid_auth', 'channel_not_found'
print(f"Got an error: {e.response['error']}")
response = requests.post('https://slack.com/api/files.upload', files=files)
Here, when I insert my Slack apps token to SLACK_API_TOKEN , it gives me error on token.
Anyone knows quick and easy way to post local images to slack?
Thanks!
The verification token can not be used for API calls. You need a user or bot token. See this answer on how to get a token: Slack App, token for Web API
You do not need to use both requests and slack to make the API call. The latter is sufficient.
Here is an example snippet for uploading a file to Slack with the official Slack library:
import os
import slack
from slack.errors import SlackApiError
# init slack client with access token
slack_token = os.environ['SLACK_TOKEN']
client = slack.WebClient(token=slack_token)
# upload file
try:
response = client.files_upload(
file='Stratios_down.jpg',
initial_comment='This space ship needs some repairs I think...',
channels='general'
)
except SlackApiError as e:
# You will get a SlackApiError if "ok" is False
assert e.response["ok"] is False
assert e.response["error"] # str like 'invalid_auth', 'channel_not_found'
print(f"Got an error: {e.response['error']}")
I can use the following way to send message when I open one website(http://localhost:api/notify).
I want to send message at the specific time(eg. 5 pm everyday)automatically, how can i do that?
from aiohttp import web
from aiohttp.web import Request, Response, json_response
async def notify() :
await _send_proactive_message()
return Response(status=201, text="Proactive messages have been sent")
APP = web.Application()
APP.router.add_get("/api/notify", notify)
if __name__ == "__main__":
try:
web.run_app(APP, host="localhost")
except Exception as error:
raise error
I have 10 groups in telegram with different name. I am able to print message with the below example code from telethon library. I also need the group name to be printed.
EG:
G10001 Bhuvan Testing (GroupName UserName/Phoneno Message)
#!/usr/bin/env python3
# A simple script to print some messages.
import os
import sys
import time
from telethon import TelegramClient, events, utils
def get_env(name, message, cast=str):
if name in os.environ:
return os.environ[name]
while True:
value = input(message)
try:
return cast(value)
except ValueError as e:
print(e, file=sys.stderr)
time.sleep(1)
session = os.environ.get('TG_SESSION', 'printer')
api_id = get_env('TG_API_ID', 'Enter your API ID: ', int)
api_hash = get_env('TG_API_HASH', 'Enter your API hash: ')
proxy = None # https://github.com/Anorov/PySocks
# Create and start the client so we can make requests (we don't here)
client = TelegramClient(session, api_id, api_hash, proxy=proxy).start()
# `pattern` is a regex, see https://docs.python.org/3/library/re.html
# Use https://regexone.com/ if you want a more interactive way of learning.
#
# "(?i)" makes it case-insensitive, and | separates "options".
#client.on(events.NewMessage(pattern=r''))#pattern=r'(?i).*\b(hello|hi)\b'))
async def handler(event):
sender = await event.get_sender()
#client.get_input_entity(PeerChannel(fwd.from_id))
#channel = await event.get_channel()
#group = event.group()
#group = event.get_group()
#print(group)
#print(utils.get_peer_id(sender))
#print(utils.get_input_location(sender))
#print(utils.get_input_dialog(sender))
#print(utils.get_inner_text(sender))
#print(utils.get_extension(sender))
#print(utils.get_attributes(sender))
#print(utils.get_input_user(sender))
name = utils.get_display_name(sender)
print(name, 'said', event.text, '!')
#print(utils.get_input_entity(PeerChannel(sender)))
#print(utils.get_input_channel(get_input_peer(channel)))
try:
print('(Press Ctrl+C to stop this)')
client.run_until_disconnected()
finally:
client.disconnect()
# Note: We used try/finally to show it can be done this way, but using:
#
# with client:
# client.run_until_disconnected()
#
# is almost always a better idea.
I also need help to send message to groups. I have gone through some answer given below, which doesn't working for me.
(Sending Telegram messages with Telethon: some entity parameters work, others don't?)
First get the chat from incoming event:
chat = await event.get_chat()
Print group name:
try:
if chat.title:
print(chat.title)
except AttributeError:
print('no such attribute present')
Send message to group:
await client.send_message(entity=chat.id,message='hi')
I am trying to use my bot to delete certain messages in a slack channel with this api call
import os
import time
import re
from slackclient import SlackClient
slack_client = SlackClient(
'xsssssseeeeeeee')
slack_mute_bot_id = None
def delete_message(slack_event):
for event in slack_event:
if event["type"] == "message":
message_text = event['text']
time_stamp = event['ts']
channel_id = event['channel']
slack_client.api_call(
'chat.delete',
channel=channel_id,
ts=time_stamp,
as_user=True
)
print(message_text + " delted")
if __name__ == "__main__":
if slack_client.rtm_connect(with_team_state=False):
slack_mute_bot_id = slack_client.api_call("auth.test")["user_id"]
while True:
# print(slack_client.rtm_read())
delete_message(slack_client.rtm_read())
time.sleep(1)
else:
print("Connection failed. Exception traceback printed above.")
I do not get any error message after doing this and the bot does not delete the message. I am using the bot user token. I have benn able to send message succesfully but the delete method does not work and still gives np responses
Refer - https://api.slack.com/methods/chat.delete
When used with a user token, this method may only delete messages
that user themselves can delete in Slack.
When used with a bot token, this method may delete only messages
posted by that bot.
I got stumbled into the same thing.