How to use python-telegram-bot repository to send message to telegram user request? - python-telegram-bot

I programmed a telegram bot for downloading torrents with python-telegram-bot repository; however, my functions seem to work on the server side and the responses appear on my terminal/console where im running the py-script and transmissionBT server, but it does not send the response back to the user. below is my code:
def get_torrent(MAGNET):
import subprocess
get_it = subprocess.run(["transmission-remote", "-a", "-D", "-o", "--utp", MAGNET])
return "*success*"
def list_torrent(LISTED):
import subprocess
get_list = subprocess.run(["transmission-remote", LISTED])
return "*listed*"
def del_torrent(TORRENT_NO):
import subprocess
del_torrent = subprocess.run(["transmission-remote", "-t", TORRENT_NO, "-r"])
return "*deleted*"
def crepttit(bot, update, args):
import time
MAGNET = " ".join(args)
media_content = get_torrent(MAGNET)
time.sleep(1)
bot.send_meessage(chat_id=update.message.chat_id, text=media_content)
def crepttl(bot, update, args):
import time
LISTED = " ".join(args)
listed_torrent = list_torrent(LISTED)
time.sleep(1)
chat_id = update.message.chat_id
bot.send_message(chat_id=chat_id, text=torrent_list)
def crepttd(bot, update, args):
import time
TORRENT_NO = " ".join(args)
deleted_torrent = del_torrent(TORRENT_NO)
time.sleep(1)
bot.send_meessage(chat_id=update.message.chat_id, text=deleted_torrent)
from telegram.ext import Updater, CommandHandler
import subprocess
import time
import os
TOKEN = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
updater = Updater(TOKEN)
dispatcher = updater.dispatcher
start_handler = CommandHandler("creptt", crepttit, pass_args=True)
dispatcher.add_handler(start_handler)
start_handler2 = CommandHandler("crepttl", crepttl, pass_args=True)
dispatcher.add_handler(start_handler2)
start_handler3 = CommandHandler("crepttd", crepttd, pass_args=True)
dispatcher.add_handler(start_handler3)
updater.start_polling()
updater.idle()

Related

Voila, jupyter and websockets: how to print?

Although the question might seem simple I can't see to find a viable way or anyway of printing the incoming messages from a threaded websocket.
Basically, I've created a jupyterlab notebook that lets me connect to a local websocket server and echo messages sent from a firecamp websocket connection. When running it on a cell (without the run button and run A.start()) I can see the prints but as soon as I hit the run button after restarting the kernal I can't see incoming messages.
Normally I would expect something like:
Function started
Someone said: test 1
Someone said: test 2
In the prints but nothing seems to apperas when hitting the run button.
The main objective is to be able to run the notebook with voila to upload to heroku but I canĀ“t seem to make the prints work. If anybody has a clue or a better idea, I'm all ears.
Thanks in advance.
PD: Code
import ipywidgets as widgets
from IPython.display import Javascript, display
import websocket
import asyncio
import nest_asyncio
import threading
import websocket
import time
import sys
import trace
import logging
from time import sleep
output_box = widgets.Output()
class KThread(threading.Thread):
"""A subclass of threading.Thread, with a kill() method."""
def __init__(self, *args, **keywords):
threading.Thread.__init__(self, *args, **keywords)
self.killed = False
def start(self):
"""Start the thread."""
self.__run_backup = self.run
self.run = self.__run
threading.Thread.start(self)
def __run(self):
"""Hacked run function, which installs the trace."""
sys.settrace(self.globaltrace)
self.__run_backup()
self.run = self.__run_backup
def globaltrace(self, frame, why, arg):
if why == 'call':
return self.localtrace
else:
return None
def localtrace(self, frame, why, arg):
if self.killed:
if why == 'line':
raise SystemExit()
return self.localtrace
def kill(self):
ws.close()
self.killed = True
def on_message(ws, message):
print(message)
def on_open(ws):
ws.send("Connected Test")
def on_close(ws, close_status_code, close_msg):
print("### closed ###")
def on_error(ws, error):
print(error)
#This illustrates running a function in a separate thread. The thread is killed before the function finishes.
def func():
print('Function started')
ws.run_forever()
ws = websocket.WebSocketApp("ws://localhost:7890", on_open=on_open,on_message = on_message, on_close = on_close,on_error = on_error)
A = KThread(target=func)
websocket.enableTrace(True)
run_button = widgets.Button(
description='Run Button',
disabled=False,
button_style='info', # 'success', 'info', 'warning', 'danger' or ''
tooltip='Run button function',
icon='play'
)
def on_run_button_clicked(b):
with output_box:
A.start()
run_button.on_click(on_run_button_clicked)
display(run_button,output_box)
This is the websocket server:
# Importing the relevant libraries
import websockets
import asyncio
# Server data
PORT = 7890
print("Server listening on Port " + str(PORT))
# A set of connected ws clients
connected = set()
# The main behavior function for this server
async def echo(websocket, path):
print("A client just connected")
# Store a copy of the connected client
print(websocket)
connected.add(websocket)
# Handle incoming messages
try:
async for message in websocket:
print("Received message from client: " + message)
# Send a response to all connected clients except sender
for conn in connected:
if conn != websocket:
await conn.send("Someone said: " + message)
# Handle disconnecting clients
except websockets.exceptions.ConnectionClosed as e:
print("A client just disconnected")
finally:
connected.remove(websocket)
# Start the server
start_server = websockets.serve(echo, "localhost", PORT)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

My application on the heroku server stops after running for 1 minute (PYTHON)

My application on the heroku server stops after running for 1 minute. Then it runs and hears commands sent to itself whenever it wants. I was wondering if it could be from the 30-minute limit, but it never worked that long.
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
import commands as c
TOKEN = "--------------"
def main():
updater = Updater(TOKEN, use_context=True)
dp = updater.dispatcher
#my commands
dp.add_handler(CommandHandler("start", c.start_command))
#while I write unknown word that the bot doesnt know
dp.add_handler(MessageHandler(Filters.text, c.wrong_command))
updater.start_polling()
updater.idle()
if __name__ == "__main__":
main()
#commands.py
from telegram.ext import Updater
def start_command(update, context):
message = "hi!"
return update.message.reply_text(message)
def wrong_command(update, context):
message = "/start only"
return update.message.reply_text(message)
requirements.txt
"""
python-telegram-bot
Procfile
web: python main.py
""" There are not many codes in the "signs".

Python Watchdog Custom Event Handler Not Firing Correctly

I'm using Python's watchdog module to listen for created events on a certain directory. Where I do some processing on newly created .csv files. When I test my code with nothing in the handler the watchdog fires correctly for all pasted/created files, but when I add my code/logic inside the handler it fires less than expected (52/60 files for example).
OS used: Windows 10, code is expected to work on a Windows server.
Python version: 3.7.3
Code:
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import pandas as pd
import numpy as np
from error_handling import ErrorHandler
import os
from timeloop import Timeloop
from datetime import timedelta
import json
from fill_data import OnMyWatch2
class OnMyWatch:
# Set the directory on watch
watchDirectory = "."
def __init__(self):
self.observer1 = Observer()
def run(self):
self.observer1.schedule(Handler() , self.watchDirectory, recursive = True)
self.observer1.start()
try:
while True:
time.sleep(1)
except:
self.observer1.stop()
print("Observer Stopped")
self.observer1.join()
class Handler(FileSystemEventHandler):
#staticmethod
def on_any_event(event):
if event.is_directory:
return None
elif event.event_type == 'created':
try:
# Event is created, you can process it now
print("Watchdog received created event - % s." % event.src_path)
pathlower = str(event.src_path).lower()
if ".csv" in pathlower:
print("File is csv file")
# Once any code is added here the problem happens
# Example:
# df = pd.read_csv(event.src_path, names= ALL_INI.columnlistbundle.split("|"), sep="|", encoding='latin-1', engine='python')
# arraySelectedColumnsBundle = ALL_INI.selectedcolumnsbundle.split(",")
# bundle_df = df[np.array(arraySelectedColumnsBundle)]
else:
print("File is not csv file")
except Exception as e:
ErrorHandler(0, 'In Observer ', '-7', 'Exception ' + str(e), '', 1, '')
if __name__ == '__main__':
if os.path.isdir("."):
watch = OnMyWatch()
watch.run()

Bot keeps executing random parts of loop

Im trying to make a bot that sends a message whenever it detects page status changes, but after 3-5 seconds it randomly sends "server is online" even tho nothing changed in the page.
import os
import discord
from dotenv import load_dotenv
import time
import requests
def check(r):
if "online" in r.text:
return True
else:
return False
online = False
load_dotenv()
TOKEN = "#hidden"
GUILD = #hidden
client = discord.Client()
#client.event
async def on_ready():
for guild in client.guilds:
if guild.name == GUILD:
break
print(
f'{client.user} is connected to the following guild:\n'
f'{guild.name}(id: {guild.id})')
channel = client.get_channel(#hidden)
last_status = check(requests.get("#page"))
while True:
if check(requests.get("#page")) == last_status:
continue
else:
if check(requests.get(#page")):
await channel.send("server is online")
last_status = check(requests.get("#page"))
else:
await channel.send("Server is offline")
last_status = check(requests.get("#page"))
client.run(TOKEN)
It's probably because you have multiple runing instance of on_readyfunction.
Discord API often send (especially during this period of overload due to the pandemic) a instruction of reconnect.
When discord.py recieve this instruction, it reconnect and call on_ready again, without killing the other.
The solution is to use asyncio.ensure_future and client.wait_until_ready to be sure there is only one instance
code:
import os
import discord
from dotenv import load_dotenv
import time
import requests
import asyncio
def check(r):
if "online" in r.text:
return True
else:
return False
online = False
load_dotenv()
TOKEN = "#hidden"
GUILD = #hidden
client = discord.Client()
async def routine():
await client.wait_until_ready()
channel = client.get_channel(#hidden)
last_status = check(requests.get("#page"))
while True:
if check(requests.get("#page")) == last_status:
continue
else:
if check(requests.get(#page")):
await channel.send("server is online")
last_status = check(requests.get("#page"))
else:
await channel.send("Server is offline")
last_status = check(requests.get("#page"))
#client.event
async def on_ready():
for guild in client.guilds:
if guild.name == GUILD:
break
print(
f'{client.user} is connected to the following guild:\n'
f'{guild.name}(id: {guild.id})')
asyncio.ensure_future(routine())
client.run(TOKEN)

Python 2.6 run time error

STEPCAFControl which is available in python2.6 but webgl module is not available. So I am trying to run this below program .
from __future__ import print_function
import sys
from OCC.STEPCAFControl import STEPCAFControl_Reader
from OCC.STEPControl import STEPControl_Reader
from OCC.IFSelect import IFSelect_RetDone, IFSelect_ItemsByEntity
from OCC.Display.SimpleGui import init_display
#from OCC.Display.WebGl import threejs_renderer
step_reader = STEPControl_Reader()
status = step_reader.ReadFile('./models/screw.step')
if status == IFSelect_RetDone: # check status
failsonly = False
step_reader.PrintCheckLoad(failsonly, IFSelect_ItemsByEntity)
step_reader.PrintCheckTransfer(failsonly, IFSelect_ItemsByEntity)
ok = step_reader.TransferRoot(1)
_nbs = step_reader.NbShapes()
aResShape = step_reader.Shape(1)
print("Success")
else:
print("Error: can't read file.")
sys.exit(0)
display, start_display, add_menu, add_function_to_menu = init_display()
display.DisplayShape(aResShape, update=True)
start_display()
#my_renderer = threejs_renderer.ThreejsRenderer(background_color="#123345")
#my_renderer.DisplayShape(aResShape)
but getting this error.
How to solve this issue? Any suggestion?

Resources