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)
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])
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).
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)
)
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')