OCPP 1.6 Remote Start Transaction - python

This is our CentralSystem.py
We have a LIVE charger configured to connect to our websocket
Ex - ws://HostName:Port/Charger Serial Number
As soon as the Charger is connected to our central system, it automatically sends us the following:
Charge point /D5200372001000010101 connected
INFO:ocpp:D5200372001000010101: receive message [2,"530","Heartbeat",{}]
Heartbeat
INFO:ocpp:D5200372001000010101: send [3,"530",{"currentTime":"2022-06-10T10:43:26Z"}]
INFO:ocpp:D5200372001000010101: receive message [2,"531","Heartbeat",{}]
Heartbeat
Issue 1 - We receive the heartbeat every 2mins but do not see anything for BootNotification and Status Notification when no vehicle is connected.
However, when the vehicle is connected, we do see a Status Notification and Heartbeats.
Issue 2 - Now, we have a mobile app that is built using Flutter which should allow us to enable "Remote Start Transaction". What is the best way to achieve this? Should we connect to the same websocket endpoint and call RemoteStartTransaction.
import asyncio
import logging
from asyncio import constants
import websockets
from datetime import datetime, timezone
from ocpp.routing import on
from ocpp.v16 import ChargePoint as cp
from ocpp.v16.enums import Action, RegistrationStatus, RemoteStartStopStatus
import ocpp.v16.enums as enums
from ocpp.v16 import call_result, call
import requests
logging.basicConfig(level=logging.INFO)
class ChargePoint(cp):
chargingProfile = {}
#on(Action.RemoteStartTransaction)
async def on_remote_start(self, id_tag, connector_id):
print("remotely starting")
return await self.remote_start_transaction()
#on(Action.BootNotification)
def on_boot_notification(self, charge_point_vendor, charge_point_model, **kwargs):
print("Boot Notification")
return call_result.BootNotificationPayload(
# current_time=datetime.utcnow().isoformat() + 'Z',
current_time=datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S') + "Z",
interval=100,
status=RegistrationStatus.accepted
)
#on(Action.StatusNotification)
def on_status_notification(self, connector_id, error_code, status, **kwargs):
print("Status Notification")
return call_result.StatusNotificationPayload()
#on(Action.Heartbeat)
def on_heartbeat(self):
print("Heartbeat")
return call_result.HeartbeatPayload(
current_time=datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S') + "Z"
)
#on(Action.Authorize)
def on_authorize(self, id_tag):
print("Authorize")
query = {'access_token': 'masterKey'}
response = requests.get('http://ec2-13-233-102-233.ap-south-1.compute.amazonaws.com:3000/chargersOnboarding/',
params=query)
data = response.json()
isFound = "false"
status = ""
for item in data['rows']:
if item['RFID'] == id_tag:
isFound = "true"
if item['status'] == 0:
status = "Accepted"
else:
status = "Expired"
break
else:
continue
if isFound == "true":
print("Authorized")
return call_result.AuthorizePayload(
id_tag_info={
# "expiryDate": "2022-02-04T13:00:00.21Z",
"expiryDate": "2023-05-19T13:00:00.21Z",
"parentIdTag": id_tag,
"status": status
},
)
else:
print("Not Authorized")
return call_result.AuthorizePayload(
id_tag_info={
"expiryDate": "",
"parentIdTag": id_tag,
"status": "Invalid"
},
)
#on(Action.StartTransaction)
def on_start_transaction(self, connector_id, id_tag, meter_start, timestamp, **kwargs):
print("START TRANSACTION COMING FROM CHARGER")
query = {'access_token': 'masterKey'}
response = requests.get('http://ec2-13-233-102-233.ap-south-1.compute.amazonaws.com:3000/chargersOnboarding/',
params=query)
data = response.json()
isFound = "false"
status = ""
for item in data['rows']:
if item['RFID'] == id_tag:
isFound = "true"
if item['status'] == 0:
status = "Accepted"
else:
status = "Expired"
break
else:
continue
if isFound == "true":
return call_result.StartTransactionPayload(
id_tag_info={
# "expiryDate": "2022-02-04T13:00:00.21Z",
"expiryDate": "2023-05-19T13:00:00.21Z",
"parentIdTag": id_tag,
"status": status
},
transaction_id=int(1)
)
else:
print("Not Authorized")
return call_result.StartTransactionPayload(
id_tag_info={
"expiryDate": "",
"parentIdTag": id_tag,
"status": "Invalid"
},
transaction_id=int(1)
)
#on(Action.StopTransaction)
def on_stop_transaction(self, transaction_id, timestamp, meter_stop, id_tag, **kwargs):
query = {'access_token': 'masterKey'}
response = requests.get('http://ec2-13-233-102-233.ap-south-1.compute.amazonaws.com:3000/chargersOnboarding/',
params=query)
data = response.json()
isFound = "false"
status = ""
for item in data['rows']:
if item['RFID'] == id_tag:
isFound = "true"
if item['status'] == 0:
status = "Accepted"
else:
status = "Expired"
break
else:
continue
if isFound == "true":
return call_result.StopTransactionPayload(
id_tag_info={
# "expiryDate": "2022-02-04T13:00:00.21Z",
"expiryDate": "2023-05-19T13:00:00.21Z",
"parentIdTag": id_tag,
"status": status
},
# transaction_id=int(1)
)
else:
print("Not Authorized")
return call_result.StopTransactionPayload(
id_tag_info={
"expiryDate": "",
"parentIdTag": id_tag,
"status": "Invalid"
},
transaction_id=int(1)
)
#on(Action.MeterValues)
def on_meter_value(self, **kwargs):
return call_result.MeterValuesPayload()
#on(Action.DataTransfer)
def on_data_transfer(self, vendor_id, message_id, data):
return call_result.DataTransferPayload(
status='Accepted'
)
#on(Action.ChangeAvailability)
def on_change_availabilty(self, connector_id, type):
return call_result.ChangeAvailabilityPayload(
status='Accepted'
)
async def send_limitation(self, limit):
response = await self.call(call.SetChargingProfilePayload(
connector_id=0,
cs_charging_profiles={
'chargingProfileId': 1,
'stackLevel': 0,
'chargingProfilePurpose': enums.ChargingProfilePurposeType.chargepointmaxprofile,
'chargingProfileKind': enums.ChargingProfileKindType.absolute,
'chargingSchedule': {
'startSchedule': datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S') + "Z",
'chargingRateUnit': enums.ChargingRateUnitType.amps,
'chargingSchedulePeriod': [{
'startPeriod': 0,
'limit': limit
}]
}
}
))
print("SEND Limitation")
print(response)
async def remote_start_transaction(self):
obj = {
'chargingProfileId': 1,
'stackLevel': 0,
'chargingProfilePurpose': enums.ChargingProfilePurposeType.chargepointmaxprofile,
'chargingProfileKind': enums.ChargingProfileKindType.absolute,
'chargingSchedule': {
'startSchedule': datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S') + "Z",
'chargingRateUnit': enums.ChargingRateUnitType.amps,
'chargingSchedulePeriod': [{
'startPeriod': 0,
'limit': 8.0
}]
},
}
print("REMOTE START!!!")
request = call.RemoteStartTransactionPayload(
id_tag='5C1DEA5A',
charging_profile=obj,
connector_id=1
)
response = await self.call(request)
print(response)
if response.status == RemoteStartStopStatus.accepted:
print("Transaction Started!!!")
else:
print("Transaction Failed to Start!!!")
print(response.status)
# websockets.send("Transaction Started!!!")
async def remote_stop_transaction(self):
print("REMOTE STOP!!!")
request = call.RemoteStopTransactionPayload(
transaction_id=1
)
response = await self.call(request)
if response.status == RemoteStartStopStatus.accepted:
print("Stopping transaction")
# websockets.send("Transaction Stopped!!!")
async def on_connect(websocket, path):
charge_point_id = path.strip('/')
cp = ChargePoint(charge_point_id, websocket)
try:
print(f'Charge point {path} connected')
await asyncio.gather(cp.start())
except websockets.exceptions.ConnectionClosed:
print(f"Charge Point {path} disconnected")
async def main():
server = await websockets.serve(
on_connect,
'0.0.0.0',
9000,
subprotocols=['ocpp1.6'],
ping_interval=None,
ping_timeout=None
)
logging.info("Server Started listening to new connections...")
await server.wait_closed()
if __name__ == '__main__':
asyncio.run(main())

> async def send_heartbeat(self, interval):
> request = call.HeartbeatPayload()
> while True:
> await self.call(request)
> await asyncio.sleep(interval)
>
> await asyncio.gather(cp.start(), cp.send_heartbeat(10))

Related

Flet telethon login page is not working (async)

I am programming Telegram Login page with Flet Gui and Telethon module. The problem I am facing is the code is not sending verification code to entered phone number nor showing any error it just stops at await client.send_code_request(phone_number). I expect the code to send code to specified number
# you can get telegram development credentials in telegram API Development Tools
api_id = ""
api_hash = ""
client = TelegramClient(StringSession(), api_id, api_hash)
def main(page: Page):
page.title = "Tel"
def startup_async():
new_event_loop().run_until_complete(startup())
def get_verif_async(phone_num):
print('ciao')
new_event_loop().run_until_complete(get_verification_code(phone_num))
def set_verif_async(phone_number, code_num):
print('Line 25 \n phone: ' + phone_number + " code: " + code_num)
new_event_loop().run_until_complete(set_verification_code(phone_number, code_num))
async def get_verification_code(phone_number):
print("29 " + phone_number)
if phone_number and re.match(r"^\+\d+$", phone_number):
print("31")
if not await client.is_user_authorized():
await client.send_code_request(phone_number)
page.go("/code_screen")
else:
print(36)
page.add(ft.Text(value='error'))
#view.update()
async def set_verification_code(phone_number, code_number):
print("42")
await client.sign_in(phone_number, code_number)
page.go("/homepage")
async def startup():
print('startup')
await client.connect()
if not await client.is_user_authorized():
page.route = "/login_screen"
else:
page.route = "/homepage"
def route_change(e):
page.views.clear()
if page.route == "/login_screen":
global phone_num_field
phone_num_field = ft.TextField(hint_text="Your phone number", expand=True)
page.views.append(
View(
"/login_screen",
[
AppBar(title=Text("Login"), bgcolor=colors.SURFACE_VARIANT),
phone_num_field,
#ElevatedButton(text='Get code', on_click= get_verif_async(phone_num_field.value)),
ElevatedButton(text='Get code', on_click=lambda x: get_verif_async(phone_num_field.value))
],
)
)
if page.route == "/code_screen":
code_field = ft.TextField(hint_text="code", expand=True)
page.views.append(
View(
"/code_screen",
[
AppBar(title=Text("Code"), bgcolor=colors.SURFACE_VARIANT),
code_field,
phone_num_field,
#ElevatedButton(text='Get code', on_click= get_verif_async(phone_num_field.value)),
ElevatedButton(text='Enter code', on_click=lambda x: set_verif_async(phone_num_field.value, code_field.value)),
ElevatedButton(text='Back', on_click=lambda x: page.go("/login_screen"))
],
)
)
if page.route == "/homepage":
page.views.append(
View(
"/homepage",
[
AppBar(title=Text("homepage"), bgcolor=colors.SURFACE_VARIANT),
],
)
)
page.update()
def view_pop(e):
page.views.pop()
top_view = page.views[-1]
page.go(top_view.route)
# async script startup
startup_async()
page.on_route_change = route_change
page.on_view_pop = view_pop
page.go(page.route)
ft.app(target=main)

Tally integration on odoo

How can I export tax analysis in invoice in tally to xml request?
url1 = "http://localhost:9000"
xml = "<ENVELOPE><HEADER><VERSION>1</VERSION><TALLYREQUEST>EXPORT</TALLYREQUEST><TYPE>DATA</TYPE>"
xml += "<ID>VoucherRegister</ID></HEADER><BODY><DESC><STATICVARIABLES>"
xml += "<EXPLODEVNUM>Yes</EXPLODEVNUM><ISVATDUTYPAID>Yes</ISVATDUTYPAID><DBINVEXPLODEFLAG>Yes</DBINVEXPLODEFLAG>"
xml+="<DBBILLEXPLODEFLAG>Yes</DBBILLEXPLODEFLAG><SVEXPORTFORMAT>$$SysName:XML</SVEXPORTFORMAT><SVFROMDATE Type='DATE'>"+self.startdate+"</SVFROMDATE><SVTODATE Type='DATE'>"+self.enddate+"</SVTODATE><VOUCHERTYPENAME>"+self.sale_name+"</VOUCHERTYPENAME><EXPLODEFLAG>Yes</EXPLODEFLAG><REPORTNAME>Ledger Cost Breakup</REPORTNAME></STATICVARIABLES>"
xml += "<TDL><TDLMESSAGE><COLLECTION><FETCH>GSTDetails.LIST</FETCH></COLLECTION></TDLMESSAGE></TDL></DESC></BODY></ENVELOPE>"
req = requests.post(url = url1,data=xml)
# res = req.text.decode("UTF-8")
response = req.text.strip().replace("&","&")
# scrubbedXML = re.sub('&.+[0-9]+;', '', response)
# print(response)
responseXML = Et.fromstring(response)
values=database.data()
print(values)
url_odoo=values['urls']
db_odoo=values['database']
email_odoo=values['email']
password_odoo=values['password']
print(url_odoo)
url=url_odoo
db=db_odoo
username=email_odoo
password=password_odoo
common = xmlrpc.client.ServerProxy('{}/xmlrpc/2/common'.format(url),allow_none=True)
uid = common.authenticate(db, username, password, {})
models = xmlrpc.client.ServerProxy('{}/xmlrpc/2/object'.format(url),allow_none=True)
for vch in responseXML.findall("./BODY/DATA/TALLYMESSAGE/VOUCHER"):
mylist=[]
mylist2=[]
myliist3=[]
stockslist=[]
amountlist=[]
quantitylist=[]
roundofflist=[]
discountlist=[]
try:
if len(vch.findall('INVENTORYENTRIES.LIST'))>=0:
try:
# stk = vch.findall("INVENTORYENTRIES.LIST").__getitem__(0).find("STOCKITEMNAME").text
for stockss in vch.findall("INVENTORYENTRIES.LIST"):
stks=stockss.find('STOCKITEMNAME').text
# print(stks)
stockslist.append(stks)
except:
stk='na'
pass
try:
for discoun in vch.findall("INVENTORYENTRIES.LIST"):
disc=float(discoun.find('DISCOUNT').text)
print(disc)
discountlist.append(disc)
# stockslist.append(stks)
except:
disc=0
discountlist.append(disc)
pass
try:
# rt = vch.findall("INVENTORYENTRIES.LIST").__getitem__(0).find("RATE").text
for rates in vch.findall('INVENTORYENTRIES.LIST'):
perrattes=rates.find('RATE').text
ratee=(re.findall(r'-?\d+\.?\d*', perrattes))
for s in ratee:
perrate=float(s)
# print(perrate)
amountlist.append(perrate)
except:
perrate=0
# print(perrate)
pass
try:
# Ktk = vch.findall("INVENTORYENTRIES.LIST").__getitem__(0).find("BILLEDQTY").text
for ktks in vch.findall('INVENTORYENTRIES.LIST'):
ktk= ktks.find('BILLEDQTY').text
billedqu=(re.findall(r'-?\d+\.?\d*', ktk))
for b in billedqu:
quan=float(b)
# print(quan)
quantitylist.append(quan)
except:
quan=1.0
quantitylist.append(quan)
# print(quan)
except:
continue
if len(vch.findall("LEDGERENTRIES.LIST"))>=0:
try:
for ro in vch.findall("LEDGERENTRIES.LIST"):
roundoff=ro.find('AMOUNT').text
round=float(roundoff)
if round>0 and round<1.0 or round< 0 and round>-1.0:
roff=float(round)
roundofflist.append(roff)
for items in vch.findall("LEDGERENTRIES.LIST"):
vall=items.find('LEDGERNAME').text
mylist.append(vall)
print(mylist)
except:
amount=0
toname='na'
# print(toname)
pass
else:
try:
amount = vch.findall("ALLLEDGERENTRIES.LIST").__getitem__(0).find("LEDGERNAME").text
except:
amount='na'
pass
try:
vch_dt=vch.find("DATE").text
vch_date=self.change_date_format(vch_dt)
except:
vch_date='na'
pass
try:
vch_led= vch.find("VOUCHERTYPENAME").text
print(vch_led)
except:
vch_led='na'
pass
try:
vch_type= vch.find("VOUCHERNUMBER").text
print(vch_type)
except:
vch_type='na'
pass
try:
vch_no= vch.find("PARTYLEDGERNAME").text
except:
vch_no= 'na'
pass
print(mylist)
try:
del mylist[0]
except:
pass
for valll in mylist:
pid=models.execute_kw(db, uid, password, 'account.tax','search',[[['name', '=',valll]]])
print(pid)
mylist2.append(pid)
# del mylist2[0]
print(mylist2,'check')
for value1 in mylist2:
try:
val2=value1[0]
except:
pass
try:
myliist3.append(val2)
print(myliist3)
except:
pass
xid=models.execute_kw(db, uid, password, 'account.invoice','search_count',[[['origin', '=', vch_type]]])
# print(xid)
lid=models.execute_kw(db, uid, password, 'account.invoice','search',[[['origin', '=', vch_type]]])
try:
sid=models.execute_kw(db,uid, password, 'res.partner','search',[[['name', '=', vch_no]]])
print(sid)
except:
continue
# print(sid)
# print(mid)
print(stockslist)
print(amountlist)
print(quantitylist)
for vill in sid:
if xid>=1:
continue
else:
rslt =models.execute_kw(db, uid, password, 'account.invoice','create',[{'partner_id': vill,
'date_invoice':vch_date,'date_due':vch_date,'journal_id':1,'state':'draft','origin':vch_type}])
print(rslt)
for st,ratt,quant,discon in zip(stockslist,amountlist,quantitylist,discountlist):
# rateval=calculate_rate(ratt,quant)
ratevals=float(ratt)
mid=models.execute_kw(db,uid, password, 'product.product','search',[[['name', '=', st]]])
print(mid,'bye')
for stockna in mid:
stock=stockna
va=models.execute_kw(db, uid, password,'product.product', 'read',[mid], {'fields': [ 'taxes_id']})
print(va)
for taxed in va:
taxfv=taxed['taxes_id']
print(taxfv,'hi')
if taxfv==[]:
taxfv=myliist3
# Oid=models.execute_kw(db, uid, password, 'account.tax','search',[[['name', '=','CGST'],['type_tax_use','=','sale']]])
# Otd=models.execute_kw(db, uid, password, 'account.tax','search',[[['name', '=','SGST'],['type_tax_use','=','sale']]])
# Oid=Oid+Otd
# taxfv=Oidk
# print(Oid)
else:
taxfv==taxfv
print(taxfv,'final')
res=models.execute_kw(db, uid, password, 'account.invoice','write',[[rslt],{'invoice_line_ids':
[(0,4, {'name': st,
'origin': vch_type,
'account_id':31,
'price_unit': ratevals,
'quantity': quant,
'is_rounding_line': True,
'discount':discon,
'uom_id': 1,
'product_id': stock,
'invoice_line_tax_ids': [[6,True, taxfv]]
}
)
]
}
]
)
res=models.execute_kw(db, uid, password, 'account.invoice','compute_taxes',[rslt])
# print(roundofflist)
for ron in roundofflist:
round=models.execute_kw(db, uid, password, 'account.invoice','write',[[rslt],{'invoice_line_ids':[(0,4, {'name': 'Rounded off',
'account_id': 284,
'price_unit': ron,
'quantity': 1})]}])
vali=models.execute_kw(db, uid, password, 'account.invoice','action_invoice_open',[rslt])

Beaglebone blue suddenly not sending signal to motors

I have created an API which is used via a web UI to control my BeagleBone Blue. The board itself controls two DC motors (for driving) and a servo motor (for turning a camera). My API receives the GET request from the UI to control the DC motors but for some reason the motors are not getting a signal. For the longest time (with the same exact code I am using now) it was working just fine. I used a volt-meter to check if a signal was being sent to the DC motors and no power is being sent. I have updated my board and made sure I have the latest version of RCPY. I am stumped as to why this is happening. The strange thing is the servo motor works perfectly fine (as it did originally).
Here is the code for my API:
import rcpy
import rcpy.motor as motor
import rcpy.servo as srv
import rcpy.clock as clock
import time
from flask import Flask, render_template, request, jsonify, make_response
from datetime import datetime
app = Flask(__name__)
#app.route('/')
def index():
return render_template('robocar.html')
#app.route('/servo/<duty>')
def move_camera(duty=0.0):
global servo_duty
if request.method == "GET":
servo = srv.Servo(1)
duty = max(min(1.0, float(duty)), -1.0)
rcpy.set_state(rcpy.RUNNING)
clk = clock.Clock(servo, 0.02)
srv.enable()
clk.start()
servo.set(duty)
time.sleep(1)
clk.stop()
srv.disable()
return _corsify_actual_response(jsonify({"response": "200"}))
else:
return _build_cors_prelight_response()
#app.route('/drive/<speed>/<direction>')
def move_car(speed=0.0, direction=0):
if request.method == "GET":
motor1_channel = 1
motor2_channel = 2
speed = float(speed)
direction = int(direction)
wheel_speeds = [speed, -speed]
if direction == 1:
motor.set(motor1_channel, wheel_speeds[0])
motor.set(motor2_channel, wheel_speeds[1])
elif direction == 4:
motor.set(motor1_channel, wheel_speeds[0])
motor.set(motor2_channel, wheel_speeds[0])
if speed >= 0.1:
time.sleep(0.5)
stop_car()
elif direction == 3:
motor.set(motor1_channel, wheel_speeds[1])
motor.set(motor2_channel, wheel_speeds[0])
elif direction == 2:
motor.set(motor1_channel, wheel_speeds[1])
motor.set(motor2_channel, wheel_speeds[1])
if speed >= 0.1:
time.sleep(0.5)
stop_car()
#time.sleep(20)
#stop_car()
return _corsify_actual_response(jsonify({"response": "200"}))
else:
return _build_cors_prelight_response()
#app.route('/brake')
def stop_car():
if request.method == "GET":
motor1_channel = 1
motor2_channel = 2
motor.set_brake(motor1_channel)
motor.set_brake(motor2_channel)
return _corsify_actual_response(jsonify({"response": "200"}))
else:
return _build_cors_prelight_response()
def _build_cors_prelight_response():
response = make_response()
response.headers.add("Access-Control-Allow-Origin", "*")
response.headers.add('Access-Control-Allow-Headers', "*")
response.headers.add('Access-Control-Allow-Methods', "*")
return response
def _corsify_actual_response(response):
response.headers.add("Access-Control-Allow-Origin", "*")
return response
if __name__ == '__main__':
app.run(host='0.0.0.0')
Here is my javascript to make requests to the API:
servo_duty = 0.0
function moveCamera(duty) {
servo_duty += duty
servo_duty = Math.max(-1.0, Math.min(1.0, servo_duty))
$.ajax({
url: "http://beaglebone.local:5000/servo/" + servo_duty,
type: "GET",
cache: false,
data: {},
success: () => {
console.log('ok');
},
error: function(result) {
console.log(result);
}
});
}
function moveCar(speed, direction) {
$.ajax({
url: "http://beaglebone.local:5000/drive/" + speed + "/" + direction,
type: "GET",
cache: false,
data: {},
success: () => {
console.log('ok');
},
error: function(result) {
console.log(result);
}
});
}
function stopCar() {
$.ajax({
url: "http://beaglebone.local:5000/brake",
type: "GET",
cache: false,
data: {},
success: () => {
console.log('ok');
},
error: function(result) {
console.log(result);
}
});
}
When a request for the DC motors is sent to the board, I get a 200 response. No errors in the console or on the API side. Any ideas? (Sorry for the wall of code).

Discord bot doesn't work and not changing status

At first my discord bot doesn't work, in this code is erorr and i can't find it, and second is that it doesn't changing status, it was changing when you put just 2 text but when trying to put client.guilds it not
#tasks.loop( seconds = 12 )
async def changeStatus():
iterationPosition = 0
status = [f' on { len(client.guilds) } servers', '~help']
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.playing, name=status[iterationPosition]))
iterationPosition = 0 if (iterationPosition is len(status) - 1) else (iterationPosition + 1)
#client.event
async def on_ready():
print( 'bot connected' )
changeStatus.start()
*Working code but with problem that he writes me answer to commands as many times as all servers he on
tasks.iterationPosition = 0
#tasks.loop( seconds = 5 )
async def changeStatus():
status = [f" on { len(client.guilds) } servers", "~help"]
await client.change_presence(
activity=discord.Activity(
type=discord.ActivityType.playing, name=status[tasks.iterationPosition]
)
)
tasks.iterationPosition = (
0
if (tasks.iterationPosition is len(status) - 1)
else (tasks.iterationPosition + 1)
)
#client.event
async def on_ready():
print( 'bot connected' )
changeStatus.start()
In your code you always assign 0 to iterationPosition at the start of loop, instead put it in "global" scope like this:
tasks.iterationPosition = 0
#tasks.loop(seconds=12)
async def changeStatus():
status = [f" on { len(client.guilds) } servers", "~help"]
await client.change_presence(
activity=discord.Activity(
type=discord.ActivityType.playing, name=status[tasks.iterationPosition]
)
)
tasks.iterationPosition = (
0
if (tasks.iterationPosition is len(status) - 1)
else (tasks.iterationPosition + 1)
)

How to make these websockets work asynchronously?

I do not know much about asynchrony, I tried to turn for loops into async for, but now only
the first element of the generator is working, the rest are ignored. What is wrong with
this code?
async def get_requests(self, data, request_type):
for x in data:
r = [
'subscribe_on_model',
{
'collection': None,
'id': None,
'recursive': ''
}
]
r[1]['collection'] = request_type
r[1]['id'] = x
yield r
async def get_results(self):
async with BaseWebsocket(self.uri) as ws:
await ws.receive()
sport_keys = list(self.sports.keys())
sport_values = list(self.sports.values())
bundle_requests = self.get_requests(sport_values, 'LineSport')
async for bundle_request in bundle_requests:
results = []
sport_name = sport_keys[sport_values.index(bundle_request[1]['id'])]
b_request = [bundle_request]
await ws.send(b_request)
b_response = await ws.receive()
bundle_ids = b_response[0][1].get('lineCountryIds')
if bundle_ids:
championship_requests = self.get_requests(bundle_ids, 'LineCountry')
async for championship_request in championship_requests:
c_request = [championship_request]
await ws.send(c_request)
c_response = await ws.receive()
championship_ids = c_response[0][1].get('lineChampionshipIds')
if championship_ids:
event_requests = self.get_requests(championship_ids, 'LineChampionship')

Categories

Resources