I'm returning a string but it says it's not working.
I'm somewhat new to discord bot coding and am confused.
Code
from python_aternos import Client
aternos = Client.from_credentials('test', '123')
servs = aternos.list_servers()
testserv = None
for serv in servs:
if serv.address == 'server.aternos.me':
testserv = serv
def handle_response(message) -> str:
p_message = message.lower()
if p_message == 'status':
return str(serv.status)
# Here the issue starts
if p_message == 'Start':
serv.start(False,True)
return "test"
# Here the issue ends
if p_message == 'help':
return "Status - Tells the status of the server.\nStart - Starts the server for people to play.\nHelp - Lists all the commands."
I tried to return a string and then use the start command but it doesn't work.
Related
I want to stream real-time data of the order book of BTC/USD using a WebSocket connection to the FTX Exchange. After the first snapshot of the order book, the WebSocket returns updates that I apply to my local reconstructed order book. To ensure that my order book is synchronized, I have to check a crc32 integer after every update. If this number matches the checksum in the message, I can be confident that my order book is well synchronized. However, sometimes the checksum is not right, and I need to reset the connection, i.e. unsubscribe to the channel and subscribe right after.
At the end of the on_messagefunction, I check if the checksum is successful. If it is not, I close the connection but I would like to clear the memory (i.e. the global objects asks, bids, checksum) and reconnect right after. How can I do it?
Should I just add a while True loop at the end? Like this one?
while True:
ws.run_forever()
I don't like this while Truesolution because it's impossible for me to stop it, I have to quit the terminal.
My code is the following
import websocket,json
import zlib
from decimal import Decimal
import binascii
from itertools import chain, zip_longest
from typing import Iterable, Sequence
asks = {}
bids = {}
checksum = {'checksum':0}
def format_e(dec):
return ('{:.' + str(len(dec.as_tuple().digits) - 1) + 'e}').format(dec)
def check_sum(
asks: Iterable[Sequence[float]], bids: Iterable[Sequence[float]]
) -> int:
asks=[[level[0],level[1]]for level in asks.items()]
bids=[[level[0],level[1]]for level in bids.items()]
order_book_hash_iterator = zip_longest(bids, asks, fillvalue=tuple())
check_string = ":".join(
(
str(token)
for ask_level, bid_level in order_book_hash_iterator
for token in chain(ask_level, bid_level)
)
)
return binascii.crc32(check_string.encode("ascii"))
def on_open(ws):
print('Opened connection')
asks.clear()
bids.clear()
subscribe_message = {'op': 'subscribe', 'channel': 'orderbook','market':'BTC/USD'}
ws.send(json.dumps(subscribe_message))
def on_message(ws,message):
js=json.loads(message)
if js['type'] == 'partial':
print('Get Snapshot')
for level in js['data']['asks']:
asks[level[0]]=level[1]
for level in js['data']['bids']:
bids[level[0]]=level[1]
checksum['checksum']=js['data']['checksum']
if js['type'] == 'update':
for level in js['data']['asks']:
if level[1]==0:
asks.pop(level[0])
else:
asks[level[0]]=level[1]
for level in js['data']['bids']:
if level[1]==0:
bids.pop(level[0])
else:
bids[level[0]]=level[1]
if check_sum(asks,bids) != js['data']['checksum']:
print('Error')
ws.close()
socket = "wss://ftx.com/ws/"
ws = websocket.WebSocketApp(socket,on_open=on_open)
ws.on_message = lambda ws,msg: on_message(ws,msg)
ws.run_forever()
How about this:
# everything up to and including `on_open` the same
class ChecksumException(Exception):
pass
def on_message(ws, message):
print(message)
js = json.loads(message)
if js['type'] == 'partial':
print('Get Snapshot')
for level in js['data']['asks']:
asks[level[0]] = level[1]
for level in js['data']['bids']:
bids[level[0]] = level[1]
checksum['checksum'] = js['data']['checksum']
if js['type'] == 'update':
for level in js['data']['asks']:
if level[1] == 0:
asks.pop(level[0])
else:
asks[level[0]] = level[1]
for level in js['data']['bids']:
if level[1] == 0:
bids.pop(level[0])
else:
bids[level[0]] = level[1]
if js['type'] == 'subscribed':
return
# so, checking this for *any* type of message, except 'subscribed'
if check_sum(asks, bids) != js['data']['checksum']:
raise ChecksumException
def main():
socket = "wss://ftx.com/ws/"
while True:
ws = None
try:
ws = websocket.WebSocketApp(socket, on_open=on_open)
ws.on_message = lambda w=ws, msg=None: on_message(w, msg)
print('Connecting...')
ws.run_forever()
print('Keyboard interrupt, stopping')
break
except ChecksumException:
ws.close()
print('Checksum error, closed')
# no break here, so the loop continues and will reconnect
if __name__ == '__main__':
main()
This is the first time t work with flask and pymongo. Anyone can tell my why and how to fix this problem ?
I had watched this video: https://www.youtube.com/watch?v=7Abxa0q4Vuk and use his code. However, it isn't work when i try to login.
It is a picture I captured when I tried to log in with an account had already register
This is the login_check code:
if(request.method == 'POST'):
req = request.form
req = dict(req)
print(req)
query = user_table.find({'uid', req['uid']})
flag = 0
temp = None
for x in query:
if(x['uid'] == req['uid']):
flag = 1
temp = x
break
if(flag == 1):
if(temp['password'] == req['password']):
return render_template('dashboard.html', uid = req['uid'])
else:
return render_template('invalid.html', message = 'incorrect password')
else:
return render_template('invalid.html', message = "User not registered")
return render_template('login.html')
This is the error:
filter must be an instance of dict, bson.son.SON, or any other type that inherits from collections.Mapping
For some reason my bot always turns off without printing any output to the command line or showing any kind of error. The bot functions properly for a few hours after being turned on. Basic code looks like this:
app = Client("my_account", '123456', '123456789abcd')
TESTING = "321"
USER_ID = "123"
chat_mapping = {TESTING: "-10011111111111", USER_ID: "-10011111111111"}
#app.on_message()
def my_handler(client, message):
if str(message.chat.id) not in chat_mapping:
return
elif str(message.chat.id) == USER_ID:
storeMsg(message)
else:
print(message.text)
app.run()
Any advice would be greatly appreciated!
if str(message.chat.id) not in chat_mapping
in this lane, your statement will check if message.chat.id is equal one of the keys of dictionary, not values.
Means your message.chat.id can't be 123 or 321.
USER_ID = some id
chat_mapping = [some ids]
#app.on_message()
def my_handler(client, message):
if str(message.chat.id) not in chat_mapping:
return
elif str(message.chat.id) == USER_ID:
storeMsg(message)
else:
print(message.text)
app.run()
I am creating a Telegram Bot using pyTelegramBotAPI that sends real-time updates of ongoing cricket matches. I want to break the loop whenever the user enters the "/stop" command. I've looked up various sources and also tried several methods to achieve the same but all in vain. The loop continues to iterate. The closest I've reached is by exiting the program by raising an error. Also, while inside the loop, the getUpdates method always returns an empty list. I've also written an issue for the same on GitHub.
def loop(match_url):
prev_info = ""
flag = 1
#continuously fetch data
while flag:
response = requests.get(match_url)
info = response.json()['score']
#display only when the score updates
if str(info) != prev_info:
prev_info = str(info)
send_msg(info)
else:
pass
send_msg(info)
#this handler needs to be fixed
#bot.message_handler(commands=['stop', 'end'])
def stop(message):
#code to break the loop
flag = 0
return
Since this was not working, I willingly used this wrong method:
while flag:
response = requests.get(match_url)
info = response.json()['score']
if str(info) != prev_info:
prev_info = str(info)
send_msg(info)
else:
pass
send_msg(info)
#bot.message_handler(commands=['stop', 'end'])
def stop(message):
bot.polling.abort = True #an arbitrary function that raises error and exits the program
Here's the whole code. I've also added my GitHub link of this code:
import requests, json, telebot
token = <TOKEN>
bot = telebot.TeleBot(token)
#parsing data from cricapi.com
def live_matches():
#here I'm using the KEY obtained from cricapi.com
curr_matches_url = "https://cricapi.com/api/cricket?apikey=<KEY>"
curr_matches = requests.get(curr_matches_url)
match_data = curr_matches.json()['data']
global unique_id_arr, score_arr
unique_id_arr, score_arr = [], []
match_details = ""
for i in match_data:
unique_id_arr.append(i["unique_id"])
for i in range(len(match_data)):
score_arr.append(match_data[i]["title"])
score_arr[i] += "\n"
match_details += str(i+1) + ". "
match_details += score_arr[i]
send_msg(match_details)
def send_msg(msg):
url2 = 'https://api.telegram.org/bot'+token+'/sendMessage'
data = {'chat_id': chat_id, 'text': msg}
requests.post(url2, data).json()
#bot.message_handler(commands=['start', 'help'])
def send_welcome(message):
bot.reply_to(message, "Howdy, how are you doing?")
global chat_id
chat_id = message.chat.id
msg = bot.reply_to(message, "Welcome to test project\nEnter the match number whose updates you want to receive")
live_matches()
bot.register_next_step_handler(msg, fetch_score)
def fetch_score(message):
chat_id = message.chat.id
match_no = message.text
#checking if the number entered is present in the displayed list
if not match_no.isdigit():
msg = bot.reply_to(message, 'Error1!\nSelect a no. from the above list only')
return bot.register_next_step_handler(msg, fetch_score)
elif 1 <= int(match_no) <= len(score_arr):
unique_id = unique_id_arr[int(match_no)-1]
global match_url
#get the data of the desired match
match_url = "https://cricapi.com/api/cricketScore?unique_id="+unique_id+"&apikey=<KEY>"
loop(match_url)
else:
msg = bot.reply_to(message, "Error2!\nSelect a no. from the above list only")
return bot.register_next_step_handler(msg, fetch_score)
def loop(match_url):
prev_info = ""
flag = 1
#continuously fetch data
while flag:
response = requests.get(match_url)
info = response.json()['score']
#display only when the score updates
if str(info) != prev_info:
prev_info = str(info)
send_msg(info)
else:
pass
send_msg(info)
#this handler needs to be fixed
#bot.message_handler(commands=['stop', 'end'])
def stop(message):
#an arbitrary function that raises error and then exits
bot.polling.abort = True
bot.polling()
"""
#currently not using
def receive_msg():
url1 = 'https://api.telegram.org/bot'+token+'/getUpdates'
response = requests.get(url1)
text = response.json()['result']
if len(text) > 0:
user_msg = text[-1]['message']['text']
return user_msg
return text
"""
You are using telebot(pyTelegramBotAPI) package in the wrong way:
Why did you create your own function send_msg where there is already send_message method in telebot exists?
You are redeclaring your "stop" handler in the loop, which is wrong!
My suggestion to you is to learn how to use the pyTelegramBotAPI properly!
Here is a demonstration code, that solves your problem:
import telebot
from time import sleep
bot = telebot.TeleBot(BOT_TOKEN)
flag = 1
#bot.message_handler(commands=['loop'])
def loop(msg):
while flag:
bot.send_message(msg.chat.id, "ping")
sleep(1)
#bot.message_handler(commands=['stop', 'end'])
def stop(msg):
global flag
flag = 0
bot.send_message(msg.chat.id, "stopped")
bot.polling(none_stop=True)
Explanation:
Declared flag as a global variable and set it to 1
"loop" handler for starting the loop that sends you "ping" message every second
"stop" handler that changes flag to 0, which terminates your running loop
I'm trying to make a simple skype bot that I can run and if a message is sent in a specific chat, that it sends one of three messages which rotate.
However I'm trying to figure out how to make it check when a message is sent into the chat.
Have so far:
import Skype4Py as skype
skypeClient = skype.Skype()
skypeClient.Attach()
def sendGroupChatMessage(topic="Topic"):
messageSent = False
messagenum = 0
for elem in skypeClient.ActiveChats:
if (messagenum == 0):
elem.SendMessage("I see")
messagenum = 1
messageSent = True
elif (messagenum == 1):
elem.SendMessage("That's amazing")
messagenum = 2
messageSent = True
elif (messagenum == 2):
elem.SendMessage("It's not your fault")
messagenum = 0
messageSent = True
if not messageSent:
for chat in skypeClient.BookmarkedChats:
if chat.Topic == topic:
chat.SendMessage("SomeMessageHere")
messageSent = True
return messageSent
if skypeClient.OnMessageStatus == 'RECEIVED':
sendGroupChatMessage()
You have to register event MessageStatus.
http://skype4py.sourceforge.net/doc/html/Skype4Py.skype.SkypeEvents-class.html
There you can find more informations.
Example code, what's resending message to sender (just echo):
import Skype4Py
skype = Skype4Py.Skype()
skype.Attach()
def onMsg(msg, status):
if status == Skype4Py.cmsReceived:
msg.Chat.SendMessage(msg.Body)
skype.RegisterEventHandler('MessageStatus', onMsg)
while 1: pass