Latency is not identified - discord.py

I was testing my code today, when suddenly an error came up saying that they could not find a reference of latency in _ _ init.py _ _. This never happened before so I don't know what to do. Here is the code of the command and the imports:
import discord
from discord.ext import commands
from pretty_help import PrettyHelp
bot = commands.Bot(command_prefix=".")
bot.load_extension('cog_admin')
bot.load_extension('cog_stuff')
bot.load_extension('cog_info')
bot.help_command = PrettyHelp()
bot.help_command = PrettyHelp(index_title="CatsyBot Help Page", no_category="Stuff")
#commands.command()
async def ping(ctx):
"""PING PONG"""
await ctx.send(f"🏓 Pong with {str(round(commands.latency, 2))}")

commands doesn't have the attribute latency, but your bot instance has
await ctx.send(f"🏓 Pong with {str(round(bot.latency, 2))}")

Related

Having two scripts publishing on the same port with zmq

I would like to have two python scripts (it can be more in real use) that publishes on the same port to a single client. Here is the code for my scripts:
server1.py:
import time
import zmq
ctx = zmq.Context()
s1 = ctx.socket(zmq.PUB)
s1.connect("tcp://127.0.0.1:5566")
for i in range(10):
s1.send_pyobj({'job':'publisher 1','yo':10})
time.sleep(5)
server2.py:
import time
import zmq
ctx = zmq.Context()
s2 = ctx.socket(zmq.PUB)
s2.connect("tcp://127.0.0.1:5566")
for i in range(10):
s2.send_pyobj({'job':'publisher 2','yo':10})
time.sleep(5)
client.py:
import zmq
ctx = zmq.Context()
c = ctx.socket(zmq.SUB)
c.bind("tcp://127.0.0.1:5566")
c.setsockopt(zmq.SUBSCRIBE, '')
while True:
msg = c.recv_pyobj()
print("MSG: ", msg)
This naive implementation works but, being new to zmq,I was wondering if it was indeed the right implementation or if there was a better way to proceed.
I think that your design is valid. However, as the comments to the answer in this similar question suggest, you might struggle to subscribe with multiple clients with this architecture.

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".

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

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()

how can i use async/await to call Future obj in python3.6

I have doubts about Python's await and hava an example,it tries to use await to fetch results from the future obj.
import time
import asyncio
import time
import random
import threading
db = {
"yzh": "pig",
"zhh": "big pig"
}
loop = asyncio.get_event_loop()
def _get_redis(username, clb):
def foo():
data = db[username]
time.sleep(0.1)
print("start clb")
clb(data)
t1 = threading.Thread(target=foo)
t1.start()
def get_redis(username):
print("start get redis")
myfuture = asyncio.Future()
def clb(result):
print("clb call")
myfuture.set_result(result)
_get_redis(username, clb)
return myfuture
async def main():
print("start main")
data = await get_redis("yzh")
print("data is {}".format(data))
loop.run_until_complete(asyncio.ensure_future(main()))
loop.close()
and i got output without future's result:
start main
start get redis
start clb
clb call
How should i use await to get the future's result?I tried many times. Thanks for your help.
As you said in your comment, you're supposed to use loop.call_soon_threadsafe when running an asyncio callback from a thread:
loop.call_soon_threadsafe(myfuture.set_result, result)
However, a better approach for calling a synchronous function from asyncio is to use loop.run_in_executor:
def _get_redis(username):
time.sleep(0.1)
return db[username]
async def get_redis(username):
return await loop.run_in_executor(None, _get_redis, username)
This way, you won't have to deal with futures and thread-safe callbacks.

Resources