I would like to set as moderator the first user who joins the conference and I'm using the twilio-python doc to help me but I didn't see anything about this.
The first participant should be moderator in order to mute, kick, etc the other one but to be honest I don't know if this is really required so I'm open to a "no need a moderator this".
Also I would like to know if the name related to the token is in the participant in order to retrieve it with this one instead of the SID. (didn't see anything in the doc)
Here the server side code :
#app.route('/call', methods=['GET', 'POST'])
def call():
resp = twilio.twiml.Response()
from_value = request.values.get('From')
to = request.values.get('To')
conferenceName = request.values.get('conferenceName')
account_sid = os.environ.get("ACCOUNT_SID", ACCOUNT_SID)
auth_token = os.environ.get("AUTH_TOKEN", AUTH_TOKEN)
app_sid = os.environ.get("APP_SID", APP_SID)
clientTwilio = TwilioRestClient(account_sid, auth_token)
elif to.startswith("conference:"):
# allows to user conference call
# client -> conference
conferencesList = client.conferences.list(friendly_name=conferenceName)
#there's no conference with the conferenceName so the first person should be the moderator and join it
if len(conferencesList) == 0
#do somestuff to set a moderator [...]
resp.dial(callerId=from_value).conference(to[11:])
else:
#there's already a conference just join it
resp.dial(callerId=from_value).conference(to[11:])
and for the "name" related to the token/client I want to use to retrieve a participant :
//http://foo.herokuapp.com/token?client=someName"
self.phone = [[TCDevice alloc] initWithCapabilityToken:token delegate:self];
NSDictionary *params = #{#"To": #"conference:foo"};
self.connection = [self.phone connect:params delegate:self];
[self closeNoddersView:nil];
//the user is connected as participant in the conference, is it possible to retrieve it with the "someName" ? (server side route which take a "someName" in param)
any clue ? :/
I found a workaround to use the client:name and no need of a moderator
a conference contains a list of participant
a participant is related to a specific call
a call contains the information in the to and from_: client:name
#app.route('/conference_kick', methods=['GET', 'POST'])
def conference():
client = TwilioRestClient(account_sid, auth_token)
conferenceName = request.values.get('conferenceName')
participantName = request.values.get('participantName')
index = 0
call = ""
# A list of conference objects
conferencesList = client.conferences.list(status="in-progress",friendly_name=conferenceName)
if len(conferencesList) == 1:
if conferencesList[0].participants:
participants = conferencesList[0].participants.list()
while index < len(participants):
call = client.calls.get(participants[index].call_sid)
array = call.from_.split(':')
if participantName == array[1]:
participants[index].kick()
return json.dumps({'code' : 200, 'success':1, 'message':participantName+' kicked'})
index += 1
return json.dumps({'code' : 101, 'success':0, 'message':participantName+' not found'})
else:
return json.dumps({'code' : 102, 'success':0, 'message':'no participants'})
else:
return json.dumps({'code' : 103, 'success':0, 'message':'no conference'})
Related
Is it possible to use multi processing in Django on a request.
#so if I send a request to http://127.0.0.1:8000/wallet_verify
def wallet_verify(request):
walelts = botactive.objects.all()
#here I check if the user want to be included in the process or not so if they set it to True then i'll include them else ignore.
for active in walelts:
check_active = active.active
if check_active == True:
user_is_active = active.user
#for the ones that want to be included I then go to get their key data.
I need to get both api and secret so then I loop through to get the data from active users.
database = Bybitapidatas.objects.filter(user=user_is_active)
for apikey in database:
apikey = apikey.apikey
for apisecret in database:
apisecret = apisecret.apisecret
#since I am making a request to an exchange endpoint I can only include one API and secret at a time . So for 1 person at a time this is why I want to run in parallel.
for a, b in zip(list(Bybitapidatas.objects.filter(user=user_is_active).values("apikey")), list(Bybitapidatas.objects.filter(user=user_is_active).values("apisecret"))):
session =spot.HTTP(endpoint='https://api-testnet.bybit.com/', api_key=a['apikey'], api_secret=b['apisecret'])
#here I check to see if they have balance to open trades if they have selected to be included.
GET_USDT_BALANCE = session.get_wallet_balance()['result']['balances']
for i in GET_USDT_BALANCE:
if 'USDT' in i.values():
GET_USDT_BALANCE = session.get_wallet_balance()['result']['balances']
idx_USDT = GET_USDT_BALANCE.index(i)
GET_USDTBALANCE = session.get_wallet_balance()['result']['balances'][idx_USDT]['free']
print(round(float(GET_USDTBALANCE),2))
#if they don't have enough balance I skip the user.
if round(float(GET_USDTBALANCE),2) < 11 :
pass
else:
session.place_active_order(
symbol="BTCUSDT",
side="Buy",
type="MARKET",
qty=10,
timeInForce="GTC"
)
How can I run this process in parallel while looping through the database to also get data for each individual user.
I am still new to coding so hope I explained that it makes sense.
I have tried multiprocessing and pools but then I get that the app has not started yet and I have to run it outside of wallet_verify is there a way to do it in wallet_verify
and when I send the Post Request.
Any help appreciated.
Filtering the Database to get Users who have set it to True
Listi - [1,3](these are user ID's Returned
processess = botactive.objects.filter(active=True).values_list('user')
listi = [row[0] for row in processess]
Get the Users from the listi and perform the action.
def wallet_verify(listi):
# print(listi)
database = Bybitapidatas.objects.filter(user = listi)
print("---------------------------------------------------- START")
for apikey in database:
apikey = apikey.apikey
print(apikey)
for apisecret in database:
apisecret = apisecret.apisecret
print(apisecret)
start_time = time.time()
session =spot.HTTP(endpoint='https://api-testnet.bybit.com/', api_key=apikey, api_secret=apisecret)
GET_USDT_BALANCE = session.get_wallet_balance()['result']['balances']
for i in GET_USDT_BALANCE:
if 'USDT' in i.values():
GET_USDT_BALANCE = session.get_wallet_balance()['result']['balances']
idx_USDT = GET_USDT_BALANCE.index(i)
GET_USDTBALANCE = session.get_wallet_balance()['result']['balances'][idx_USDT]['free']
print(round(float(GET_USDTBALANCE),2))
if round(float(GET_USDTBALANCE),2) < 11 :
pass
else:
session.place_active_order(
symbol="BTCUSDT",
side="Buy",
type="MARKET",
qty=10,
timeInForce="GTC"
)
print ("My program took", time.time() - start_time, "to run")
print("---------------------------------------------------- END")
return HttpResponse("Wallets verified")
Verifyt is what I use for the multiprocessing since I don't want it to run without being requested to run. also initialiser starts apps for each loop
def verifyt(request):
with ProcessPoolExecutor(max_workers=4, initializer=django.setup) as executor:
results = executor.map(wallet_verify, listi)
return HttpResponse("done")
```
i'm a python novice, trying to learn and be useful at work at the same time
we use DespatchBay to send parcels. they have a SOAP API which i don't entirely understand, and am using an SDK they released.
before booking a collection and producing a label my code queries the api to get available services, and available dates, and returns what i think are custom object-types containing the info i need. i want to extract and then print information from these objects so that i can confirm the correct details have been used.
postcode = "NW1 4RY"
street_num = 1
recipient_address = client.find_address(postcode, street_num)
print (recipient_address)
yields:
(AddressType){
CompanyName = "London Zoo"
Street = "Regents Park"
Locality = None
TownCity = "London"
County = None
PostalCode = "NW1 4RY"
CountryCode = "GB"
}
i can see there's a dictionary there, and i want to drill down into it to extract details, but i don't understand the "(AddressType)" before the dictionary - how do i get past it and call values from the dictionary?
AddressType has some ref here but it doesn't shine much light for me
thanks for any help you can offer!
full code: sdk ref
import os
from despatchbay.despatchbay_sdk import DespatchBaySDK
from pprint import pprint
api_user = os.getenv('DESPATCH_API_USER')
api_key = os.getenv('DESPATCH_API_KEY')
client = DespatchBaySDK(api_user=api_user, api_key=api_key)
sender_id = '5536'
# inputs
postcode = "NW1 4RY"
street_num = 1
customer = "Testy Mctestson"
phone = "07666666666"
email = "testicles#tested.com"
num_boxes = 2
collection_date = '2022-09-11'
recipient_address = client.find_address(postcode, street_num)
recipient = client.recipient(
name=customer,
telephone=phone,
email=email,
recipient_address=recipient_address
)
print (recipient_address)
parcels = []
parcel_names = []
for x in range(num_boxes):
parcelname = "my_parcel_" + str(x + 1)
parcel_names.append(parcelname)
for my_parcel in parcel_names:
go_parcel = client.parcel(
contents="Radios",
value=500,
weight=6,
length=60,
width=40,
height=40,
)
parcels.append(go_parcel)
sender = client.sender(
address_id=sender_id
)
shipment_request = client.shipment_request(
parcels=parcels,
client_reference=customer,
collection_date=collection_date,
sender_address=sender,
recipient_address=recipient,
follow_shipment='true'
)
services = client.get_available_services(shipment_request)
shipment_request.service_id = services[0].service_id
dates = client.get_available_collection_dates(sender, services[0].courier.courier_id)
print(customer + "'s shipment of",num_boxes, "parcels will be collected from: ",recipient['RecipientAddress'], "on", dates[0])
shipment_request.collection_date = dates[0]
added_shipment = client.add_shipment(shipment_request)
client.book_shipments([added_shipment])
shipment_return = client.get_shipment(added_shipment)
label_pdf = client.get_labels(shipment_return.shipment_document_id)
label_pdf.download('./' + customer + '.pdf')
You do not know exactly how they store the data inside of their object, even if it looks like a dictionary. you could run print(dir(recipient_address)) and see what the "inside of the object looks like". once you get the output you start inspecting which attributes or methods may have the data you want. Of course, you should always follow the published contract for interacting withe these objects, as the implementation details can always change. I've examine the source code of this object published here
https://github.com/despatchbay/despatchbay-python-sdk/blob/master/despatchbay/despatchbay_entities.py#L169
It turns out that it doesn't use a dictionary. It looks like you are meant to just access the data via attributes like follows:
recipient_address.company_name
recipient_address.street
recipient_address.locality
recipient_address.town_city
recipient_address.county
recipient_address.postal_code
recipient_address.country_code
I agree, their python sdk could use improved documentation..
In the following locust file, we are sending two user details. This works fine when we run with 2 users. However, when we run the same with more than 2 users (for example 5 users), then it starts failing for that remaining new users ( i.e 3 users).
import json
from locust import User, HttpUser, task, between, SequentialTaskSet,
HttpLocust
USER_CREDENTIALS = [
("abc#xyz.com", "Yahoo#123"),
("xyz#xyz.com", "Yahh-69-Wrap")
]
class CLMLoginTaskSet(SequentialTaskSet):
hostname_app2 = "http://app2.stage.cloud.local"
hostname_app1 = "http://app1.stage.cloud.local"
port = "8090"
username = "NOT_FOUND"
password = "NOT_FOUND"
access_token_value1 = None
#task
def userlist(self):
if len(USER_CREDENTIALS) > 0:
self.username, self.password = USER_CREDENTIALS.pop()
#task
def generate_clm_token(self):
print("username", self.username)
print("password", self.password)
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
clm_response =
self.client.post(self.hostname_app2+":"+self.port+"/oauth2/access?
grant_type=password&username="+self.username+"&password="+self.password",
headers=headers)
print("CLM Response", clm_response.text)
json_clm_response = clm_response.json()
access_token_value = json_clm_response['access_token']
print("This is the access token value", access_token_value)
self.access_token_value1 = access_token_value
class CLMLogin(HttpUser):
tasks = [CLMLoginTaskSet]
host = ""
wait_time = between(1, 2)
It should repeat and use the same user list if we start the load test with more users. How to achieve this ?
you have 2 credentials and popping them on start. pop removes the item from the list so after your first 2 users the list is empty and has nothing to pop. Try increasing credentials if you still want to use pop method or you can just access one credential with random.choice method without popping so next user can still use that. Beware that some users will have same user so they can affect each other depending on how the system works.
I have a smart contract address for security tokens, and certain functions of it are protected by access rights, for which I have an address to access those functions, however I am not able to figure out, how to call that function by specifying the rights.
from web3 import HTTPProvider, Web3, exceptions
w3 = Web3(HTTPProvider('https://ropsten.infura.io/RPw9nHRS7Ue47RaKVvHM'))
contract_address = '0x635209612bf0e830ac348ef30357ee4f0e5bf560'
provider_abi = [{"anonymous":False,"inputs":[{"indexed":False,"name":"addr","type":"address"},{"indexed":False,"name":"propertyKey","type":"bytes32"},{"indexed":False,"name":"propertyValue","type":"bytes32"}],"name":"PropertySet","type":"event"},{"constant":False,"inputs":[{"name":"_addr","type":"address"},{"name":"_propertyKey","type":"bytes32"},{"name":"_propertyValue","type":"bytes32"}],"name":"setProperty","outputs":[{"name":"","type":"bool"}],"payable":False,"stateMutability":"nonpayable","type":"function"},{"constant":True,"inputs":[{"name":"_addr","type":"address"},{"name":"_propertyKey","type":"bytes32"}],"name":"getProperty","outputs":[{"name":"","type":"bytes32"}],"payable":False,"stateMutability":"view","type":"function"}]
instance = w3.eth.contract(
address=Web3.toChecksumAddress(contract_address),
abi = provider_abi
)
user_address = "0x25BEADE120E501D7b984498D196eFe4AbE6a11F6"
country_key = "country"
country_byte_32 = Web3.toHex(Web3.toBytes(text=country_key))
print(country_byte_32) # Prints 0x636f756e747279
country_val = "IN"
country_val_byte_32 = Web3.toHex(Web3.toBytes(text=country_val))
print(country_val_byte_32) # Prints 0x494e
try:
result = instance.call().setProperty(user_address,country_byte_32,country_val_byte_32)
print(result) # Prints False
except exceptions.MismatchedABI as ve :
print(ve)
import traceback
print(traceback.format_exc())
Can someone tell me, how do I provide the access right address?
To put the value in the form field you can do it like this
result = instance.call({"from": user_address }).setProperty(user_address,country_byte_32,country_val_byte_32)
We have an application that is basically just a form submission for requesting a team drive to be created. It's hosted on Google App Engine.
This timeout error is coming from a single field in the form that simply does typeahead for an email address. All of the names on the domain are indexed in the datastore, about 300k entities - nothing is being pulled directly from the directory api. After 10 seconds of searching (via the Python Google Search API), it will time out. This is currently intermittent, but errors have been increasing in frequency.
Error: line 280, in get_result raise _ToSearchError(e) Timeout: Failed to complete request in 9975ms
Essentially, speeding up the searches will resolve. I looked at the code and I don't believe there is any room for improvement there. I am not sure if increasing the instance class will improve this, it is currently an F2. Or if perhaps there is another way to improve the index efficiency. I'm not entirely sure how one would do that however. Any thoughts would be appreciated.
Search Code:
class LookupUsersorGrpService(object):
'''
lookupUsersOrGrps accepts various params and performs search
'''
def lookupUsersOrGrps(self,params):
search_results_json = {}
search_results = []
directory_users_grps = GoogleDirectoryUsers()
error_msg = 'Technical error'
query = ''
try:
#Default few values if not present
if ('offset' not in params) or (params['offset'] is None):
params['offset'] = 0
else:
params['offset'] = int(params['offset'])
if ('limit' not in params) or (params['limit'] is None):
params['limit'] = 20
else:
params['limit'] = int(params['limit'])
#Search related to field name
query = self.appendQueryParam(q=query, p=params, qname='search_name', criteria=':', pname='query', isExactMatch=True,splitString=True)
#Search related to field email
query = self.appendQueryParam(q=query, p=params, qname='search_email', criteria=':', pname='query', isExactMatch=True, splitString=True)
#Perform search
log.info('Search initialized :\"{}\"'.format(query) )
# sort results by name ascending
expr_list = [search.SortExpression(expression='name', default_value='',direction=search.SortExpression.ASCENDING)]
# construct the sort options
sort_opts = search.SortOptions(expressions=expr_list)
#Prepare the search index
index = search.Index(name= "GoogleDirectoryUsers",namespace="1")
search_query = search.Query(
query_string=query.strip(),
options=search.QueryOptions(
limit=params['limit'],
offset=params['offset'],
sort_options=sort_opts,
returned_fields = directory_users_grps.get_search_doc_return_fields()
))
#Execute the search query
search_result = index.search(search_query)
#Start collecting the values
total_cnt = search_result.number_found
params['limit'] = len(search_result.results)
#Prepare the response object
for teamdriveDoc in search_result.results:
teamdriveRecord = GoogleDirectoryUsers.query(GoogleDirectoryUsers.email==teamdriveDoc.doc_id).get()
if teamdriveRecord:
if teamdriveRecord.suspended == False:
search_results.append(teamdriveRecord.to_dict())
search_results_json.update({"users" : search_results})
search_results_json.update({"limit" : params['limit'] if len(search_results)>0 else '0'})
search_results_json.update({"total_count" : total_cnt if len(search_results)>0 else '0'})
search_results_json.update({"status" : "success"})
except Exception as e:
log.exception("Error in performing search")
search_results_json.update({"status":"failed"})
search_results_json.update({"description":error_msg})
return search_results_json
''' Retrieves the given param from dict and adds to query if exists
'''
def appendQueryParam(self, q='', p=[], qname=None, criteria='=', pname=None,
isExactMatch = False, splitString = False, defaultValue=None):
if (pname in p) or (defaultValue is not None):
if len(q) > 0:
q += ' OR '
q += qname
if criteria:
q += criteria
if defaultValue is None:
val = p[pname]
else:
val = defaultValue
if splitString:
val = val.replace("", "~")[1: -1]
#Helps to retain passed argument as it is, example email
if isExactMatch:
q += "\"" +val + "\""
else:
q += val
return q
An Index instance's search method accepts a deadline parameter, so you could use that to increase the time that you are willing to wait for the search to respond:
search_result = index.search(search_query, deadline=30)
The documentation doesn't specify acceptable value for deadline, but other App Engine services tend to accept values up to 60 seconds.