DialogFlow (Can you have one master agent which controls other agents?) - dialogflow-es

Something like Angular where its modularized. Modules are a great way to organize an application and extend it with capabilities from external libraries.
Have one Master agent where its connected to different agents?

You can make multiple agents then write a script where you would call the agents using the sdk based on the condition.
Each agent would have a project id which will be used to make the connection to the agent.
Below is example how to it in python:
import dialogflow
def detect_intent_texts(project_id, session_id, text)
session_client = dialogflow.SessionsClient()
session = session_client.session_path(project_id, session_id)
text_input = dialogflow.types.TextInput(text=text)
query_input = dialogflow.types.QueryInput(text=text_input)
response = session_client.detect_intent(
session=session, query_input=query_input)
session_id = initialize_session_id_from_application
text = get_text_from_application
if condition == 1:
res = detect_intent_texts(project_id_1, session_id, text)
elif condition == 2:
res = detect_intent_texts(project_id_2, session_id, text)
else:
res = detect_intent_texts(project_id_3, session_id, text)
You can view the user query using res.query_result.query_text, and detected intent using res.query_result.intent.display_name.
Do note that different intent will create different sessions internally.
Hope it helps.

Related

simple question on how to put a value on a group picker field - Scriptrunner for Jira Cloud

I'm having difficulties in proceeding with a script.
I scripted it with scriptrunner to improve the runtime of this automation. Basically what I need is for the script to do a check on a cascading jira cloud field and depending on option 1 AND option 2, I need the script to define a third field with one of the available options. This third field is a group picker field in jira cloud
My difficulty is in line 18, on the put function, so far what i have is this:
import groovy.json.JsonSlurper
import java.util.logging.Logger
def key = issue.key
def epics = get("/rest/api/2/search").queryString('jql', "key = '${key}'").asObject(Map).body
def requests_brasil = epics["issues"]["fields"]["customfield_10830"]["value"]
def requests_child = epics["issues"]["fields"]["customfield_10830"]["child"]["value"][0]
def solver_group = ""
logger.info(requests_brasil)
logger.info(requests_child)
if (requests_brasil == "Active Directory Group" && request_child == "Create New Active Directory Group") {
solver_group = "ServiceDesk-N1"
}
#from here is where i am finding it difficult to continue
def result = put("/rest/api/2/issue/${issue.key}")
.header('Content-Type', 'application/json')
.body({
fields: [
"customfield_10583": solver_group
]
})
.asString()
I don't have a knowledge of advancing in scriptrunner, so I believe my code is very simple in complexity, I'm open to suggestions for improvements too
I would like to know how I can make this put function work on this group picker field
Thanks for the support guys

Flask Assign different ID to different website visitor at the same time and write their input information into json file

I am using FLASK to create a series of websites for doing a survey, I want to run the server once and invite multiple participants to help me fill the form on the webpage.
1.
I am aiming for assigning a unique ID (currently using python UUID) to different visitors and save their input info into different JSON files. (eg,. A's id is 00001, after he submiting the form, the info will be saved in the file named 00001.json, B's info will be saved in 00002.json). For now, I only create a UUID when the server start running, every visitor's information will be rewritten in the same file, (what I want is n visitors will produce n files).
2.
I want to show different survey questions to different visitors.
I am quite confused about if it is related to Multi-thread? Session? Cookie? Flask-login.
Hope someone can guide me on this. Thanks a lot!
assignmentID = str(uuid.uuid1())
jsonFileName = "upload/" + assignmentID + ".json"
jsonSurvey = "upload/" + assignmentID + "_survey.json"
#it ideally should randomly select different info/question no. to different user
Idx = random.sample(range(0,10), 5)
#app.route("/")
def index():
return render_template("surveyPage.html", data=Idx)
# write input information from webpage to JSON files, each visitor ideally should have their own JSON file.
#app.route("/record")
def recordData():
if request.method == 'POST':
print("READING FORM")
with open(jsonSurvey, 'w') as f:
json.dump(request.form, f)
f.close()
if __name__ == "__main__":
app.config['JSON_SORT_KEYS'] = False
app.run(debug = True)
# app.config["TEMPLATES_AUTO_RELOAD"] = True
You are defining assignmentID, jsonFileName, jsonSurvey and Idx outside of the request handlers which means they will be set once: when the server starts. jsonSurvey will therefore have the same value for each request which means that every new survey you store will overwrite the previous one.
The solution is to move the definition into the request handlers so that you genereate new values on each request.
#app.route("/")
def index():
Idx = random.sample(range(0,10), 5)
return render_template("surveyPage.html", data=Idx)
#app.route("/record")
def recordData():
if request.method == 'POST':
assignmentID = str(uuid.uuid1())
jsonFileName = "upload/" + assignmentID + ".json"
jsonSurvey = "upload/" + assignmentID + "_survey.json"
print("READING FORM")
with open(jsonSurvey, 'w') as f:
json.dump(request.form, f)
f.close()

How to stop threads in an infinte loop by passing in a True or False variable?

I have been searching for days for a solution to this issue, if anyone can point me in the right direction, I will be so grateful.
I have been writing a program that allows a user to create multiple trading bots at the same time, each bot is created as an individual thread that makes an api call to Binance for the latest market data and evaluates this data with conditional statements and place trades accordingly. The code I am using for this has been trimmed to only the essential parts for simplicity.. I have a Bot class...
class Bot(threading.Thread):
def __init__(self, symbol, time, exposure, strategy):
threading.Thread.__init__(self)
self.symbol = symbol
self.time = time
self.exposure = exposure
self.strategy = strategy
self.stop_bot = False
def scanner(self):
while self.stop_bot == False:
client = Client(self.api_key, self.secret_key, {"verify": True, "timeout": 20})
price_data = client.get_klines(symbol=self.symbol, interval=self.time_interval)
self.df = pd.DataFrame(price_data)
self.modified_df = pd.DataFrame(price_data)
time.sleep(10)
def kill(self):
self.stop_bot = True
And the Bot class is called from the bot manager terminal class...
class Bot_Manager:
def __init__(self):
self.bot_list = []
bot = object
def terminal(self):
while True:
user_input = input('(1) Create new Bot (2) Stop Bot')
if user_input == '1':
symbol = 'OMGUSDT'
time = '1D'
exposure = 1000
strategy = 'SAR'
bot_name = input('name your bot: ')
bot = Bot(symbol=symbol, time=time, exposure=exposure, strategy=strategy, bot_name=bot_name)
scanner_thread = threading.Thread(target=bot.scanner, daemon=True)
scanner_thread.name = bot_name
scanner_thread.start()
self.bot_list.append(scanner_thread)
elif user_input == '2':
for thread in threading.enumerate():
print(thread.name)
print(self.bot_list)
user_input = input('Bot to stop: ')
i = int(user_input)
print(self.bot_list[i])
Now I am able to create multiple threads / bots by repeatedly selecting option 1. However the issue I am facing is stopping these threads when a user selects option 2. If for example I create 3 bots and name them Bot A, Bot B and Bot C.. when I enumerate this in a for loop, i get the following:
MainThread
Bot A
Bot B
Bot C
and when I store each thread into a list and print the list I see the following:
[<Thread(Bot A, started 8932)>, <Thread(Bot B, started 12268)>, <Thread(Bot C, started 13436)>]
I would like the user to be able to select the thread / bot they want to stop from the list, so in this example if the user types 1, it should return the thread <Thread(Bot B, started 12268)>and stop this thread by passing the variable stop_bot = True. However I haven't had much luck with this.
When I call the function bot.kill() it only stops the last thread that was created, so for this example, Bot C. When it runs again, it doesn't remove any other thread. Is there anyway to pass in the variable stop_bot = True on an already created object / thread? Or is there another method to this that I have overlooked... Any help would be greatly appreciated....
I managed to find a solution to this by adding multiple bots to a data frame and passing this into the bot class. 1 thread was created to iterate through the data frame and by removing rows of the data frame, the bots would be removed.

How to add check in embed definitions?

Hi there I'm trying to add checks to my embed definitions that return the users information from the sql database.
What I'd like to achieve is to check if the user has set a gametag and then if the data isn't there then don't show it on their profile.
However, I'm was able to pass a check to see if the user data is in the database if the result is None it will turn Steam None where as I rather not show it altogether.
Here is what I'm working with:
#commands.group(invoke_without_command=True)
async def profile(self, ctx, user: discord.Member=None):
user = user or ctx.author
db = sqlite3.connect('profiles.sqlite')
cursor = db.cursor()
cursor.execute(f"SELECT profile FROM profile WHERE username={user.id}")
result = cursor.fetchone()
cursor.execute(f"SELECT steam FROM profile WHERE username={user.id}")
result2 = cursor.fetchone()
if result is None:
await ctx.send(f"{user.display_name}'s bio has not been created yet.")
elif result4:
steam = f"**Steam** [{result2[0]}](http://steam.com/{result2[0]})" #return data from database.
else:
steam = "" # return nothing if nothing returned from database.
desc = f"{(result[0])} \n\n {steam}:" # define a embed description as f-string
embed = discord.Embed(title=f"{user.name}'s Profile", description=desc, color=user.colour)
await ctx.send(embed=embed)```
If I understand correctly, you do not want result2[0] to be None, whereas you are checking for result to be None. Make sure to check for both result2 and result2[0] to be not None and that should fix it.
Also, if that is supposed to stop the embed creation, you might want to return after the await ctx.send(...) (under "if result == None:").

i have to compare mobile price from flipkart and amazon and present on html taking user input in it

print there difference in which I used dataframe I want to make HTML page in which we get user input and passed in python code and print which site has the best buy
mobile_name=input('pls enter a mobile model: ')
driver = webdriver.Firefox(executable_path='E:\\python\\geckodriver')
driver.get('https://www.flipkart.com/');
search_box = driver.find_element_by_name('q')
search_box.send_keys(mobile_name)
search_box.submit()
mobile_url=driver.current_url
containers = page_soup.findAll('div', {'class': '_1UoZlX'})
l = len(containers)
price = page_soup.findAll('div', {'class': '_1vC4OE _2rQ-NK'})
fl_price=[]
for i in range(1):
pr1=(price[i].text)
fl_price.append(pr1)
fl_price1=[]
for i in fl_price: fl_price1.append(i.replace("₹","")) driver.get('https://www.amazon.in/'); search_box = driver.find_element_by_name('field-keywords') search_box.send_keys(mobile_name) search_box.submit() mobile_url=driver.current_url data=requests.get(mobile_url) page_soup=bs4.BeautifulSoup(data.text,'html.parser') containers = driver.find_elements_by_class_name("sg-col-inner") l = len(containers) price = driver.find_elements_by_class_name("a-price-whole") am_price=[] for i in range(1): pr=(price[i].text) am_price.append(pr) Al_price1=[] for i in am_price: Al_price1.append(i.replace("₹|,","")) d = {'Model Name': [mobile_name],'Flipkart price':fl_price1, 'Amazon price':am_price} df = pd.DataFrame(data=d) df['Flipkart price'] = df['Flipkart price'].str.replace(',', '') df['Amazon price'] = df['Amazon price'].str.replace(',', '') df['Savings'] = df['Flipkart price'].astype(float) - df['Amazon price'].astype(float) df['Savings'] =df['Savings'].abs()
I want HTML page where it accepts user input passed on while submitting the made it should execute the file
Seems you want suggestion,
To return HTML from python you suppose to go with framework.
since you are a beginner start to implement the same using flask a python based based micro framework.
or if your requirement is big then go with django
if you only want to return serve HTML via python then go with CGI
Remember.. to use all these 3 you need server like apache or wsgi.
for CGI you can do the same with apache or with python server. for django, flask it will comes with testing server like WSGI

Resources