Python pypresence discord - discord.py

It does not give errors, but the statute simply does not appear in the discord.
from pypresence import Presence
from time import time
RPC = Presence("848861630226104320")
btns = [
{
"label": "YouTube",
"url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ"
}
]
RPC.connect()
# noinspection PyTypeChecker
RPC.update(
start=time(),
buttons=btns,
)
input()
I reinstalled the library many times and wrote that everything is there, but nothing works. Any suggestions?

Related

How do you get proxy integration in scrapy-playwright working?

I'm trying to set up proxy for scrapy-playwright but always get the error
playwright._impl._api_types.Error: net::ERR_TIMED_OUT at http://whatismyip.com/
=========================== logs ===========================
navigating to "http://whatismyip.com/", waiting until "load"
when executing the code:
from scrapy import Spider, Request
from scrapy_playwright.page import PageMethod
class ProxySpider(Spider):
name = "check_proxy_ip"
custom_settings = {
"PLAYWRIGHT_LAUNCH_OPTIONS": {
"proxy": {
"server": "http://host:port",
"username": "user",
"password": "pass",
},
},
"PLAYWRIGHT_DEFAULT_NAVIGATION_TIMEOUT": "300000",
}
def start_requests(self):
yield Request("http://whatismyip.com",
meta=dict(
playwright=True,
playwright_include_page=True,
playwright_page_methods=[PageMethod('wait_for_selector', 'span.ipv4-hero')]
),
callback=self.parse,
)
def parse(self, response):
print(response.text)
The proxies tried are paid and working as checked, and the DOWNLOAD_DELAY in settings.py is set to DOWNLOAD_DELAY=30. This happens whether PLAYWRIGHT_DEFAULT_NAVIGATION_TIMEOUT is set to 0, 10000, or 300000 (as copied in the code above). What is the problem here?

Kubernetes Pods Restart Notification alerts on my team's channel

My Pods are running on AKS Cluster. Whenever my pods restarted, I had to get a notification on my team's channel, are there any articles or commands to configure the notification?
For that same, you can use tools or application like botkube : https://www.botkube.io/
Also check the Kubewatch : https://github.com/bitnami-labs/kubewatch
You can also implement the Grafana with the Prometheus and Alert manager for monitoring and getting the alert system. : https://github.com/grafana-operator/grafana-operator
However if you can not looking for any tools or applications you can write down the custom script of python, node or any language you are good with and monitor any pod restart event and send the slack hook event.
Sharing one example python code with check the POD running or crashing and send a notification to slack you can update the logic as per need.
from kubernetes import client, config, watch
import json
import requests
import time
logger = logging.getLogger('k8s_events')
logger.setLevel(logging.DEBUG)
# If running inside pod
#config.load_incluster_config()
# If running locally
config.load_kube_config()
v1 = client.CoreV1Api()
v1ext = client.ExtensionsV1beta1Api()
w = watch.Watch()
mydict={}
webhook_url = '';
while True:
pod_list= v1.list_namespaced_pod("default");
for i in pod_list.items:
for c in i.status.container_statuses:
if(c.ready == True):
if i.metadata.name in mydict:
print("Inside mydict If");
print("Pod updated : ",i.metadata.name);
print("My dict value : ",mydict);
mydict[i.metadata.name]['end_time'] = i.status.conditions[1].last_transition_time;
dt_started = mydict[i.metadata.name]['start_time'].replace(tzinfo=None);
dt_ended = mydict[i.metadata.name]['end_time'].replace(tzinfo=None);
duration = str((dt_ended - dt_started).total_seconds()) + ' Sec';
fields = [{"title": "Status", "value": "READY", "short": False }, {"title": "Pod name", "value": i.metadata.name, "short": False }, {"title": "Duration", "value": duration, "short": False }, {"title": "Service name", "value": c.name, "short": False } ]
if c.name not in ('conversation-auto-close-service-scheduler','admin-service-trail-fllow-up-scheduler','bot-trial-email-scheduler','conversation-service-scheduler','faq-service-scheduler','nlp-service-scheduler','refresh-add-on-scheduler','response-sheet-scheduler'):
text = c.name + " Pod is started";
data = {"text": text, "mrkdwn": True, "attachments" : [{"color": "#FBBC05", "title": "Pod Details", "fields" : fields, "footer": "Manvar", "footer_icon": "https://cdn.test.manvar.com/assets/manvar-icon.png"}, ], }
print("Final data to post: ",data);
response = requests.post(webhook_url, data=json.dumps(data),headers={'Content-Type': 'application/json'});
del mydict[i.metadata.name]
if response.status_code != 200:
raise ValueError('Request to slack returned an error %s, the response is:\n%s' % (response.status_code, response.text));
time.sleep(1);
else:
mydict[i.metadata.name] = {"start_time": i.status.conditions[0].last_transition_time,"end_time": i.status.conditions[1].last_transition_time};
I tried out Botkube but I did not want to publicly expose my cluster endpoint, so I wrote the following script based on the code from #Harsh Manvar. You can connect this to Teams using the Incoming Webhook Teams app from Microsoft.
from kubernetes import client, config
import json
import requests
import time
def monitorNamespace(namespace: str, webhookUrl: str):
v1 = client.CoreV1Api()
pod_list= v1.list_namespaced_pod(namespace);
podsNotRunning = {"Namespace": namespace, "Pods": []}
for pod in pod_list.items:
status = getPodStatus(pod)
if status != "Running":
podsNotRunning["Pods"].append({"Podname": pod.metadata.name, "status": status})
if len(podsNotRunning)>0:
sendAlert(podsNotRunning, webhookUrl)
def sendAlert(podsNotRunning, webhookUrl):
print(podsNotRunning)
response = requests.post(webhookUrl, data=json.dumps(podsNotRunning),headers={'Content-Type': 'application/json'});
if response.status_code != 200:
print('Response error:', response)
def getPodStatus(pod: client.models.v1_pod.V1Pod) -> str:
status = pod.status.phase
containerStatus = pod.status.container_statuses[0]
if containerStatus.started is False or containerStatus.ready is False:
waitingState = containerStatus.state.waiting
if waitingState.message is not None:
status = waitingState.reason
return status
if __name__ == "__main__":
# If running inside pod:
#config.load_incluster_config()
# If running locally:
config.load_kube_config()
webhookUrl = 'http://webhookurl'
namespace='default
interval = 10
while True:
monitorNamespace(namespace, webhookUrl)
time.sleep(interval)

Google Cloud Speech API. Help getting Google's own example to work

Trying to get hints to work with Google Cloud Speech API. However, I can not get Google's own example to work for me. I get the same result with and without hints. I believe the following code is what the documentation is recommending:
Here is my script:
#!/usr/bin/python
import os
import base64
import googleapiclient.discovery
speech_file = os.path.join(
os.path.dirname(__file__),
'resources',
'shwazil_hoful.flac')
with open(speech_file, 'rb') as speech:
b64speech = base64.urlsafe_b64encode(speech.read())
service = googleapiclient.discovery.build('speech', 'v1')
service_request = service.speech().recognize(
body={
"config": {
"encoding": "FLAC", # raw 16-bit signed LE samples
"sampleRateHertz": 16000, # 16 khz
"languageCode": "en-US", # a BCP-47 language tag
"speechContexts": [{
"phrases": ["hoful","shwazil"]
}]
},
"audio": {
"content": b64speech
#"uri":"gs://cloud-samples-tests/speech/brooklyn.flac"
}
})
response = service_request.execute()
recognized_text = 'Transcribed Text: \n'
for i in range(len(response['results'])):
recognized_text += response['results'][i]['alternatives'][0]['transcript']
print(recognized_text)
Output:
it's a swazzle Hopple day
I was expecting:
it's a swazzle hoful day
Is there anything I am doing wrong?
I've tried both Python2 and Python3

karma-typescript: import JS file with Async keyword

I'm using karma-typescript, with this karma config file :
karmaTypescriptConfig: {
compilerOptions: {
target: "es5",
lib: ["dom", "es2015", "es2017"]
},
bundlerOptions: {
transforms: [require("karma-typescript-es6-transform")()]
}
},
In my spec files, I have this code :
import {} from './local/lib.js'
In my lib.js, I have this code :
async function() {}
When executing my tests with npm test, I have this error :
ERROR [source-reader.karma-typescript] Error parsing code: Unexpected token (X:Y) in /local/lib.js
If I remove the async keyword, everything is alright.
How can I edit my karma config file to fix the error ?
According to an issue in the Github of the karma-typescript package (https://github.com/monounity/karma-typescript/issues/344), there is an undocumented flag which may help you test code which contains ES2017 code:
karmaTypescriptConfig: {
compilerOptions: {
target: "es5",
lib: ["dom", "es2015", "es2017"]
},
bundlerOptions: {
acornOptions: {
ecmaVersion: 8,
},
transforms: [require("karma-typescript-es6-transform")()]
}
},
This flag made appear our issues with the async keyword. However, there is still an issue with the spread syntax (...array) in our code, even using this flag. If anyone knows an answer how to also fix that, I will happily extend my answer.

Why does vscode delete golang source on save

why can't save these line of code in vscode with golang extension
package app
import (
"fmt"
)
//this is just func
func TestingHello(){
fmt.Println("Hissssss")
}
only the package app stays and remaining part got deleted on save in vscode.
config both editor.formatOnSave and editor.codeActionsOnSave in the settings.json:
"[go]": {
"editor.formatOnSave": false,
"editor.codeActionsOnSave": {
"source.organizeImports": false
},
},
"go.formatTool": "gofmt",
Basically, your formatOnSave is on for go which is causing this problem.
To disable it, go to your Command Palette (Ctrl+Shift+P), type in "configure language specific settings", and look for Go.
You should now see a json file where you can add the following setting to it:
"editor.formatOnSave": false
This is how the json file looks like if you just have on setting modified for go:
{
"window.zoomLevel": 1,
"[go]": {
"editor.formatOnSave": false,
}
}
By default Format Tool is set to "goreturns" in settings.json, change it to "fmt":
{
"go.formatTool": "gofmt"
}
Now you can comment the imports:
import (
"fmt"
// "reflect"
// "math/rand"
)
I had a similar issue that was caused by not having the right case on method names.
In the following code import "fmt" would disappear.
package main
import "fmt"
func main() {
fmt.println("hello world")
}
Solution I should be calling Println NOT println ! Note the uppercase P. Once changed goreturns adds the import instead of removing it.
Ctrl+Shift+P --> Configure Language Specific Settings
"editor.insertSpaces": false,
"editor.formatOnSave": **false,**
"editor.codeActionsOnSave": {
"source.organizeImports": **false**
}
}
}
That seems strange.
I can understand the import disappearing (as in issue 748) because of goreturns (github.com/sqs/goreturns) removing unused import. But that shouldn't apply in your case.
But if almost everything disappears, that means the file fails to be saved, and revert to its original content.
Maybe another process is keeping an handle on that file, preventing the save operation to proceed.
The reason why this happening is because of what you imported, you didn't use it in the program, so Golang deletes unnecessary dependencies.
For me, the changes did not take effect until I re-loaded the window.
For every change, run
Cmd + Shift + P
>Developer: Reload Window
It's a simple answer that I found:
package main
import (
"fmt"
)
func main() {
fmt.Println("Hello")
}
`
Make sure P is capital of Println , I spent hours to find out this error.
On VScode just press (CTRL + SHIFT + P ).
Then, Click on "Configure language-specific settings"
and select GO lang.
Just paste code
"[go]": {
"editor.insertSpaces": false,
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.organizeImports": true
}
}

Resources