How to let the user specify a variable in embed? - function

Tried to pass a variable entered by the user, but nothing happens
Tried to pass only in description and field_value!
Sample code:
#application_checks.has_permissions(administrator=True)
#slash_command(description="")
async def ???(self,
interaction: nextcord.Interaction,
title: str,
description: str,
field_name: str,
field_value: str):
embed = nextcord.Embed(
title=title,
description=description,
color=0xffffff
)
embed.add_field(
name=field_name,
value=field_value,
inline=False
)
await interaction.response.send_message(embed=embed, ephemeral=True)
Tried:
f"{description}"
format(description)
description.format
Etc...

You need to actually set the embed description to the string you're creating.
#application_checks.has_permissions(administrator=True)
#slash_command(description="")
async def ???(
self,
interaction: nextcord.Interaction,
title: str,
description: str,
field_name: str,
field_value: str
):
# not sure _how_ you want your description formatted - so just doing this for now
formatted_description = f"{description} {field_name} {field_value}"
embed = nextcord.Embed(
title=title,
description=formatted_description,
color=0xffffff
)
embed.add_field(
name=field_name,
value=field_value,
inline=False
)
await interaction.response.send_message(embed=embed, ephemeral=True)
So:
format the description how you want to format it before creating the embed and save it as a variable
use that variable as the embed description when you created the embed

Related

I'm having some trouble parsing data from a csv file to create test runs in Azure DevOps via the REST API using Groovy

I'm having some trouble parsing data from a csv file to create test runs in Azure DevOps via the REST API using Groovy.
The csv file is tab delimited because one of the columns (rTestPoints) requires commas for grouping the test points to its test run.
This is the column I'm having trouble with
rTestPoints
1754478, 1754479
The csv file is formatted as follows:
runIds runNames runOwners rTestPoints runStartDate runCreatedDate runCompletedDate
1463132 NewSuite1 (Manual) Test Owner 1754478, 1754479 2022-05-27T18:51:12Z 2022-05-27T18:51:12Z 2022-05-27T18:51:13.283Z
but when I pass this data to the method to create the test run, the testPoints are getting parsed in the body of the Post call as:
"pointIds": [
"1754478, 1754479"
]
which isn't associating the test run to the test point. Quotes need to surround both values as in:
"pointIds": [
"1754478", "1754479"
]
}
I tried adding quotes to the csv input file but it results in:
"pointIds": [
"\"1754478\", \"1754479\""
]
Any ideas on how I can parse this data correctly by surrounding both values with quotes?
I'm sure there's something I can do to handle this.
Thanks!
Also here's some snippets of the code I'm using.
Here's how I've designed the csv file:
def csvdata = []
def columns = ['runIds','runNames', 'runOwners', 'rTestPoints', 'runStartDate', 'runCreatedDate', 'runCompletedDate']
BufferedReader br = new BufferedReader(new FileReader(fileName))
br.readLine(); // consume first line and ignore
br.splitEachLine(" ") {values ->
csvdata.add([columns, values].transpose().collectEntries())
}
here's the block of code where I'm passing in the data from csv
for (int i=0; i <csvdata.size(); i++) {
String runIds = csvdata.runIds[i]
String runName = csvdata.runNames[i]
String runOwner = csvdata.runOwners[i]
String rTestPoints = csvdata.rTestPoints[i]
String runState = "InProgress"
String runStartDate = csvdata.runStartDate[i]
String runCreateDate = csvdata.runCreatedDate[i]
String runCompletedDate = csvdata.runCompletedDate[i]
String comment = "test run copied from project ${srcproject} and test plan ${srcPlanId} from runID: ${runIds}"
try {
createTestRun = testManagementService.createTestRun(collection, targetProject, targetTestPlanId, rTestPoints, comment, runOwner, runName, runState, runCreateDate, runStartDate, runCompletedDate)
} catch (e) {
log.error("Unable to create test run ${runIds} for test point(s) ${rTestPoints} in project: ${targetProject}")
}
Here's the method in the TestManagementService to create the 'test run'
public def createTestRun(collection, project, testplanId, testpointIds, comment, owner, name, state, createdDate, startedDate, completedDate) {
def eproject = URLEncoder.encode(project, 'utf-8')
eproject = eproject.replace('+', '%20')
def uri = "${genericRestClient.getTfsUrl()}/${collection}/${eproject}/_apis/test/runs?api-version=6.0&bypassRules=True&suppressNotifications=true"
def body = ['name': name, 'state': state, 'comment': comment, 'createdDate': createdDate, 'starteDate': startedDate, 'completedDate': completedDate, 'owner': [ 'displayName': owner], 'plan': [ 'id': testplanId], 'pointIds': [ testpointIds ] ]
String sbody = new JsonBuilder(body).toPrettyString()
def result = genericRestClient.rateLimitPost(
requestContentType: ContentType.JSON,
contentType: ContentType.JSON,
uri: uri,
body: sbody,
//headers: [Accept: 'application/json'],
query: ['api-version': '5.1-preview.1' ]
)
return result
}
What I had to do was pass instead of passing the rTestPoints as a string, I had to pass it as a "List"
String rTestPoints = csvdata.rTestPoints[i]
List<String> rTestPointsList = rTestPoints.split(',') as List
Then pass rTestPointsList to the createTestRun method
createTestRun = testManagementService.createTestRun(collection, targetProject, targetTestPlanId, **rTestPointsList**, comment, runOwner, runName, runState, runCreateDate, runStartDate, runCompletedDate)

A python client to ContextualWeb News API using RapidAPI

I am trying to consume ContextualWeb News API. The endpoint is described here:
https://rapidapi.com/contextualwebsearch/api/web-search
Here is the request snippet in Python as described in RapidAPI:
response = unirest.get("https://contextualwebsearch-websearch-v1.p.rapidapi.com/api/Search/NewsSearchAPI?autoCorrect=true&pageNumber=1&pageSize=10&q=Taylor+Swift&safeSearch=false",
headers={
"X-RapidAPI-Host": "contextualwebsearch-websearch-v1.p.rapidapi.com",
"X-RapidAPI-Key": "XXXXXX"
}
)
How do I send the request and parse the response? Can you provide a complete code example for the News API?
use the python version 3.X for below code.Below is the complete example example where I am passing string Taylor Swift and parsing response...Let me know if you stuck anywhere
import requests # install from: http://docs.python-requests.org/en/master/
# Replace the following string value with your valid X-RapidAPI-Key.
Your_X_RapidAPI_Key = "XXXXXXXXXXXXXXXXXXX";
# The query parameters: (update according to your search query)
q = "Taylor%20Swift" # the search query
pageNumber = 1 # the number of requested page
pageSize = 10 # the size of a page
autoCorrect = True # autoCorrectspelling
safeSearch = False # filter results for adult content
response = requests.get(
"https://contextualwebsearch-websearch-v1.p.rapidapi.com/api/Search/NewsSearchAPI?q={}&pageNumber={}&pageSize={}&autocorrect={}&safeSearch={}".format(
q, pageNumber, pageSize, autoCorrect, safeSearch),
headers={
"X-RapidAPI-Key": Your_X_RapidAPI_Key
}
).json()
# Get the numer of items returned
totalCount = response["totalCount"];
# Get the list of most frequent searches related to the input search query
relatedSearch = response["relatedSearch"]
# Go over each resulting item
for webPage in response["value"]:
# Get the web page metadata
url = webPage["url"]
title = webPage["title"]
description = webPage["description"]
keywords = webPage["keywords"]
provider = webPage["provider"]["name"]
datePublished = webPage["datePublished"]
# Get the web page image (if exists)
imageUrl = webPage["image"]["url"]
imageHeight = webPage["image"]["height"]
imageWidth = webPage["image"]["width"]
thumbnail = webPage["image"]["thumbnail"]
thumbnailHeight = webPage["image"]["thumbna`enter code here`ilHeight"]
# An example: Output the webpage url, title and published date:
print("Url: %s. Title: %s. Published Date:%s." % (url, title, datePublished))

Scala + Slick how to map json to the table column with datatype as blob

I need to map json values to the table using slick and store whole json as a blob in the same table as well.
def createJob(jobs: JobEntity): Future[Option[Long]] =
db.run(job returning job.map((_.id)) += jobs)
My Json contains values like
id(long),name(string), type(string)
while the table I am trying to map has columns
id(long),name(string), type(string),json_data(blob)
I have JobEntity class as
case class JobEntity(id: Option[Long] = None, name: String, type: String) {
require(!jobname.isEmpty, "jobname.empty")
}
How do I map the json to the json_data column?
Slick supports the following LOB types: java.sql.Blob, java.sql.Clob, Array[Byte] (see the documentation)
Therefore you want to use one of these types. Your table definition could look like this:
case class Job(id: Option[Long] = None, name: String, `type`: String, json_data: java.sql.Blob)
class Jobs(tag: Tag) extends Table[Job](tag, "jobs") {
def id = column[Option[Long]]("id")
def name = column[String]("name")
def `type` = column[String]("type")
def json_data = column[java.sql.Blob]("json_data")
def * = (id, name, `type`, json_data) <> (Job.tupled, Job.unapply)
}

Play framework - save data to database by parameters in URL

I'm new to the Play Framework, and Scala language. I want to save some data to database only by running URL with specified parameters.
For example I want to run url like:
/DeviceData?device_ID=1&insertDate=2013-01-01&windDirection=50&device_ID=1&insertDate=2013-01-02&windDirection=5
and after that in the database two new records would be inserted (with Device_ID, insertDate and windDirection).
Right now I'm trying to save only one record at once (I don't know how to read list of elements and save them) but event that it's not working. There is no error, it's just not inserted.
DeviceData model
case class DeviceData(data_ID: Long, device_ID: Long, insertDate: String, windDirection: Double)
object DeviceData{
var deviceDataList = new HashMap[Long, DeviceData]
var data_ID = 0L
def nextId(): Long = { data_ID += 1; data_ID}
def createDeviceData(device_ID: Long, insertDate: String, windDirection: Double) :Unit = {
DB.withConnection { implicit connection =>
SQL(
"""
INSERT INTO devicedata(device_ID, insertDate, windDirection)
VALUES ({device_ID}, {insertDate}, {windDirection})
"""
).
on("device_ID" -> device_ID, "insertDate" -> insertDate, "windDirection" -> windDirection).
executeInsert()
}
}
def list(): List[DeviceData] = { deviceDataList.values.toList }
}
DeviceDatas controller
object DeviceDatas extends Controller {
val deviceDataForm = Form(
tuple(
"device_ID" -> of[Long],
"insertDate" -> nonEmptyText,
"windDirection" -> of[Double]
)
)
def listDeviceData() = Action {
Ok(views.html.deviceData(DeviceData.list(), deviceDataForm))
}
def createDeviceData(device_ID: Long, insertDate: String, windDirection: Double) = Action { implicit request =>
deviceDataForm.bindFromRequest.fold(
errors => BadRequest(views.html.deviceData(DeviceData.list(), errors)),
{ case (device_ID, insertDate, windDirection) => {
DeviceData.createDeviceData(device_ID, insertDate, windDirection)
Redirect(routes.DeviceDatas.listDeviceData)
}
}
)
}
}
deviceData.scala.html - it's simple one, just to check if there is any new inserted record.
#(deviceDatas: List[DeviceData], deviceDataForm: Form[(Long, String, Double)])
#import helper._
#main("DeviceDatas"){
<h3>#deviceDatas.size DeviceData(s)</h3>
}
routes file for /deviceDatas
GET /deviceDatas controllers.DeviceDatas.listDeviceData
POST /deviceDatas controllers.DeviceDatas.createDeviceData(device_ID: Long, insertDate: String, windDirection: Double)
Could You help me with that how to insert the data into database, and if there is any possibility to put list of elements with few records to insert. Also what's the best way to insert DateTime (yyyy-MM-dd hh:mm:ss) into URL parameters in Play Framework? I'm stuck and I don't know how to do it.
UPDATED
Thanks Zim-Zam O'Pootertoot for the answer. Unfortunately I need to use parameters, because I'm sending the data through the router. But anyway one more thanks to You because I'll use json in the future.
I decided to not use List of parameter as I said before, but for one new record I'm sending one request (for example: to add 6 new records to the database I need to run 6 times URL on the router:
/DeviceData?device_ID=1&insertDate=2013-01-01&windDirection=50
And my problem was solved by changing the route file to:
GET /deviceDatas controllers.DeviceDatas.listDeviceData
GET /deviceDatas controllers.DeviceDatas.createDeviceData(device_ID: Long, insertDate: String, windDirection: Double)
To pass in data for multiple records, and also to pass in DateTime data, send the data in the request's json body instead of as url params
http://www.playframework.com/documentation/2.2.x/ScalaBodyParsers
http://www.playframework.com/documentation/2.2.x/ScalaJson
Action(parse.json) { implicit request =>
(request.body \ "records") match {
case arr: JsArray => arr.value.foreach(json => {
val deviceId = (json \ "device_ID").as[Long]
val date = (json \ "insertDate").as[String]
val windDirection = (json \ "windDirection").as[Double]
// insert data in database
})
case _ => throw new IllegalArgumentException("Invalid Json: records must be a JsArray")
}}
The json for your records might look something like
{"records" : [
{"device_ID" : 123, "insertDate" : "2014-03-01 12:00:00", "windDirection" : 123.45},
{"device_ID" : 456, "insertDate" : "2014-03-02 12:00:00", "windDirection" : 54.321}]}

How retrieve a JSON object in a GSP view from a controller

The controller has the next method (I'm recycling my implementation of the bootstrap-file-upload plugin):
def uploadImage() {
String baseName;
String imageExtension = uploadPhotoService.imagesExtension;
String thumbnailExtension = uploadPhotoService.thumbnailsExtension;
switch(request.method){
case "GET":
def results = []
String imagesDirectoryPath = uploadPhotoService.getImageDirectoryDestinationPath(params.idAlojamiento);
def dir = new File(imagesDirectoryPath)
if( dir.exists() ) {
dir.eachFile {
baseName = uploadPhotoService.removeFileExtension(it.getName());
results << [
name: baseName,
size: it.length(),
url: createLink(controller:'alojamiento', action:'picture', params:[imageName: baseName + "." + imageExtension, idAlojamiento: params.idAlojamiento]),
thumbnail_url: createLink(controller:'alojamiento', action:'thumbnail', params:[imageName: baseName + "." + thumbnailExtension, idAlojamiento: params.idAlojamiento]),
delete_url: createLink(controller:'alojamiento', action:'deleteImage', params:[baseName: baseName, idAlojamiento: params.idAlojamiento]),
delete_type: "DELETE"
]
}
}
render results as JSON
break;
case "POST":
(...)
In the view, there is the next line:
<g:include controller="alojamiento" action="uploadImage" params="[idAlojamiento:alojamientoInstance.id]"/>
So the Internet browser shows a text line with the content of the JSON results variable:
[{"name":"boceto escaleras patio","size":37567,"url":"/AlojamientoPrototipo/alojamiento/picture?imageName=boceto+escaleras+patio.jpg&idAlojamiento=1","thumbnail_url":"/AlojamientoPrototipo/alojamiento/thumbnail?imageName=boceto+escaleras+patio.png&idAlojamiento=1","delete_url":"/AlojamientoPrototipo/alojamiento/deleteImage?baseName=boceto+escaleras+patio&idAlojamiento=1","delete_type":"DELETE"},
(...)
I don't want to show that text line. I want to loop through all images. I think it could work:
<g:each in="${results}">
<img src="${it.thumbnail_url}"/>
</g:each>
How could I to pass the results JSON variable to the GSP view to loop through it?
To get a variable like that:
<g:set var="results" value="${g.include(controller: "alojamiento", action: "uploadImage", params: [idAlojamiento:alojamientoInstance.id])}" />
<g:each in="${JSON.parse(results)}">
<img src="${it.thumbnail_url}"/>
</g:each>
However I should mention that you should just send this down the initial call. Put the logic in a service to make it reusable.
Edit: Forgot it was a string