Making commands so only certain servers can do it - discord.py

I am wanting only certain servers to be able to use this feature shown below.
I want to know if there is a way to make it so only certain server ids can use this command.
#bot.command(pass_context = True)
async def shittymeme(ctx):
api = 'https://api.imgflip.com/get_memes'
response = requests.get(api)
url = random.choice(response.json()['data']['memes'])
url = url['url']
await bot.say( embed = discord.Embed(color = 0x0072ff, title = "Here you go").set_image(url = url))

Assuming you have a whitelist of server ids, you can take advantage of the Checks feature built into the commands extension.
whitelist = ["id1", "id2"]
def is_in_server_list(server_list):
def predicate(ctx):
return ctx.message.server.id in server_list
return commands.check(predicate)
#bot.command(pass_context = True)
#is_in_server_list(whitelist)
async def shittymeme(ctx):
api = 'https://api.imgflip.com/get_memes'
response = requests.get(api)
url = random.choice(response.json()['data']['memes'])
url = url['url']
await bot.say( embed = discord.Embed(color = 0x0072ff, title = "Here you go").set_image(url = url))

Related

Why is my attacchment serializer not saving data?

I have messages and attachments to them (photos, documents, etc.). When I pass data to the serializer, I find that it is empty.
serializer:
class MessageAttachmentSerializer(serializers.ModelSerializer):
file = serializers.FileField()
class Meta:
model = MessageAttachment
fields = ("file", "message", "size")
view:
#api_view(["POST"])
def stuff_message(request):
data = request.data.copy()
data["sender"] = request.user.id
serializer = MessageSerializer(data=data, context={"request": request})
serializer.is_valid(True)
saved_msg = serializer.save()
if request.FILES:
data["message"] = saved_msg
attachment_serializer = MessageAttachmentSerializer(data=data, context={"request": request}, many=True)
attachment_serializer.is_valid(True)
attachment_serializer.save()
try:
bot.send_message(serializer.validated_data["receiver"].telegram_id, text=serializer.validated_data["text"])
except ApiTelegramException:
return Response("Chat undefined.", status=status.HTTP_404_NOT_FOUND)
return Response()
My message serializer works fine. When trying to output validated_data or data from MessageAttachment I get an empty list. Doesn't throw errors.
Corrected to:
#api_view(["POST"])
def stuff_message(request):
request.data._mutable = True
request.data["sender"] = request.user.id
serializer = MessageSerializer(data=request.data)
serializer.is_valid(True)
saved_msg = serializer.save()
request.data["message"] = saved_msg.id
attachments = []
for attachment in request.FILES.getlist("file"):
record = request.data
record["file"] = attachment
attachment_serializer = MessageAttachmentSerializer(data=record)
attachment_serializer.is_valid(True)
saved_attachment = attachment_serializer.save()
attachments.append(saved_attachment.file)
try:
bot.send_message(serializer.validated_data["receiver"].telegram_id, text=serializer.validated_data["text"])
for attachment in attachments:
bot.send_document(serializer.validated_data["receiver"].telegram_id, attachment.file)
except ApiTelegramException:
return Response("Chat undefined.", status=status.HTTP_404_NOT_FOUND)
return Response()
Just a guess but make sure you are returning the .data attribute on your serialized data as in:
output = MessageAttachmentSerializer(data=data).data
Reference: https://www.django-rest-framework.org/api-guide/serializers/
It was the "many" argument. It looks like cases with one file and several need to be handled differently when creating data through a serializer.

Issues with forms using Ruby Mechanize

I am trying to automate getting a certain report from a web service my company uses. I've been using the Mechanize gem, and I was able to get other reports from the same service using it.
When I submit the form that generates the report, all I get back in response is headers of the CSV. It should be returning more than that, obviously.
I've used the Chrome Dev Tools to see what the expected values for each field are, and I've mimicked them. No matter what I try, though, I just can't get the service to return the expected values.
What should I try? What might I be doing wrong?
Edit: Code in question
#loginpage = 'service_uri'
agent = Mechanize.new
login_page = agent.get #loginpage
login_form = login_page.form
email_field = login_form.field_with(name: "Email")
password_field = login_form.field_with(name: "Password")
email_field.value = 'service_login'
password_field.value = 'service_password'
page = login_form.submit
transaction_page = page.link_with(text: 'Transaction History').click
transaction_form = transaction_page.form_with(action: "/reports/transactionhistory/transactionreportexport")
transaction_form['IncludeSupplier'] = "false"
transaction_form['IncludeBrand'] = "false"
transaction_form['IncludeClassification'] = "false"
transaction_form['IncludeAttributes'] = "false"
transaction_form['IncludeScannedCode'] = "false"
transaction_form['Reason'] = ""
transaction_form['Type'] = "AddItem"
transaction_form['WarehouseId'] = "0"
transaction_form['UserLocaleInfo.Locale'] = "en-US"
transaction_form['UserLocaleInfo.TimeZoneOffset'] = "-360"
dateToday = Date.today-2
dateTomorrow = Date.today-1
transaction_form['StartDate'] = "\"#{dateToday.to_s}-T06:00:00.000Z\""
transaction_form['EndDate'] = "\"#{dateTomorrow.to_s}-T05:59:59.999Z\""
transaction_form.submit

Convert Suport Ticket to TASK Odoo 9

Is it possible convert Suport Ticket to Project > Task.
Task Title = Suport subject, Task Description = Suport Description...
Example:
I use this modul https://www.odoo.com/apps/modules/9.0/website_support/
In support ticket i want add:
Below is new function def generate_task(self): how generate new TASK from that.
class WebsiteSupportTicketCompose(models.Model):
_name = "website.support.ticket.compose"
ticket_id = fields.Many2one('website.support.ticket', string='Ticket ID')
partner_id = fields.Many2one('res.partner', string="Partner", readonly="True")
email = fields.Char(string="Email", readonly="True")
subject = fields.Char(string="Subject", readonly="True")
body = fields.Html(string="Message Body")
template_id = fields.Many2one('mail.template', string="Mail Template", domain="[('model_id','=','website.support.ticket')]")
#api.onchange('template_id')
def _onchange_template_id(self):
if self.template_id:
values = self.env['mail.compose.message'].generate_email_for_composer(self.template_id.id, [self.ticket_id.id])[self.ticket_id.id]
self.body = values['body']
#api.one
def send_reply(self):
#Send email
values = {}
email_wrapper = self.env['ir.model.data'].get_object('website_support','support_ticket_reply_wrapper')
values = email_wrapper.generate_email([self.id])[self.id]
values['model'] = "website.support.ticket"
values['res_id'] = self.ticket_id.id
send_mail = self.env['mail.mail'].create(values)
send_mail.send()
#(Depreciated) Add to message history field for back compatablity
self.env['website.support.ticket.message'].create({'ticket_id': self.ticket_id.id, 'content':self.body.replace("<p>","").replace("</p>","")})
#Post in message history
#self.ticket_id.message_post(body=self.body, subject=self.subject, message_type='comment', subtype='mt_comment')
staff_replied = self.env['ir.model.data'].get_object('website_support','website_ticket_state_staff_replied')
self.ticket_id.state = staff_replied.id
#api.one
def generate_task(self):
values = {}
print(self.ticket_id.id)
print(self.email)
print(self.subject)
print(self.body.replace("<p>","").replace("</p>",""))
#How this data insert in new TASK
Any simple solution?
Try below code:
#api.multi
def generate_task(self,cr, uid, ids, context=None):
Task = self.pool["project.task"]
vals = {
"name": "TEST",
"description": "DESCRIPTION",
}
task_id = Task.create(cr,uid,vals,context=None)
task = Task.browse(cr,uid,task_id,context=None)

django rest framework writable nested serializer returns empty nested data

I'm following this link (http://www.django-rest-framework.org/api-guide/relations/#writable-nested-serializers) to write nested serializer. But when I pop the 'vars' from validated_data in the create method of HostSerializer, I found it's empty.
I'm using django 1.9.2 and django restframework 3.3.2.
My model:
class Host(models.Model):
name = CharField(max_length=20, primary_key=True)
vm_cpu = IntegerField(default=2)
vm_mem = IntegerField(default=2048)
create_vm = BooleanField(default=True)
def __unicode__(self):
return('%s' % (self.name))
class Variable(models.Model):
name = CharField(max_length=10)
value = CharField(max_length=20)
host = models.ForeignKey(Host, related_name='vars')
def __unicode__(self):
return('%s=%s' % (self.name, self.value))
Serializer
class VariableSerializer(ModelSerializer):
class Meta:
model = Variable
class HostSerializer(ModelSerializer):
vars = VariableSerializer(many=True)
class Meta:
model = Host
def create(self, validated_data):
# i set a break point here and found vars_data is empty
vars_data = validated_data.pop('vars')
host = Host.objects.create(**validated_data)
for v in vars_data:
Variable.objects.create(host = host, **v)
return host
This is the problem I found vars_data is an empty list:
def create(self, validated_data):
# i set a break point here and found vars_data is empty
vars_data = validated_data.pop('vars')
Here's the rest of the code
admin.py
class VariableAdmin(admin.ModelAdmin):
list_display = ['name', 'value']
class HostAdmin(admin.ModelAdmin):
list_display = ['name']
admin.site.register(Variable, VariableAdmin)
admin.site.register(Host, HostAdmin)
urls.py
router = DefaultRouter()
router.register(r'variables', VariableViewSet, base_name='variables')
router.register(r'hosts', HostViewSet, base_name='hosts')
urlpatterns = [
url(r'^', include(router.urls)),
]
views.py
class VariableViewSet(ModelViewSet):
queryset = Variable.objects.all()
serializer_class = VariableSerializer
class HostViewSet(ModelViewSet):
queryset = Host.objects.all()
serializer_class = HostSerializer
My test program
post.py
import json
import requests
file = 'host.json'
url = 'http://localhost:8001/test_nest/hosts/'
with open(file, 'r') as f:
j = f.read()
data = json.loads(j)
r = requests.post(url, data = data)
print r.text
And here's the test data
host.json
{
"name": "host4",
"vars": [
{
"name": "var2-a",
"value": "a1"
},
{
"name": "var2-b",
"value": "a2"
}
],
"vm_cpu": 2,
"vm_mem": 2048,
"create_vm": true
}
I'm new to django. So I'm wondering if it's something simple and obvious. Did I use the wrong viewset? Did I post to the wrong URL? Or I setup the URL structure wrong?
I your serializers try using...
def update(self, instance,validated_data):
instance.vars_data = validated_data.get('vars',instance.vars)
instance.host = Host.objects.create(**validated_data)
for v in vars_data:
v,created=Variable.objects.create(host = host, **v)
instance.v.add(v)
return host
The following code works for me. Maybe you can try it:
models.py
class UserProfile(AbstractUser):
pass
class TobaccoCert(models.Model):
license = models.CharField(primary_key=True, max_length=15)
license_image = models.ImageField(upload_to="certs", blank=True, null=True, verbose_name='cert image')
views.py
class UserViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet):
serializer_class = UserRegSerializer
...
def create(self, request, *args, **kwargs):
data = request.data
# here i make my nested data `certs` and update it to data
image_data = request.FILES.get('images')
_license = data.get('username', None)
certs = {'license': _license, 'license_image': image_data}
data['certs'] = certs
serializer = self.get_serializer(data=data)
serializer.is_valid(raise_exception=True)
user = self.perform_create(serializer) # save it
ret_dict = serializer.data
payload = jwt_payload_handler(user)
ret_dict["token"] = jwt_encode_handler(payload) # 获取token
ret_dict["name"] = user.name if user.name else user.username
headers = self.get_success_headers(serializer.data)
return Response(ret_dict, status=status.HTTP_201_CREATED, headers=headers)
serializer.py
class CertSerializer(serializers.ModelSerializer):
pass
class UserRegSerializer(serializers.ModelSerializer):
# [Serializer relations - Django REST framework](https://www.django-rest-framework.org/api-guide/relations/#writable-nested-serializers)
# this line is vars of your code
certs = CertSerializer(many=True,write_only=True)
...
password = serializers.CharField(
style={'input_type': 'password'}, help_text="passowrd", label="passowrd", write_only=True,
)
class Meta:
model = User
fields = ("username", "mobile", "password", 'province', 'city', 'dist', 'code', 'certs')
def create(self, validated_data):
"""
"""
# here we get certs
certs_data = self.initial_data.get('certs')
# just pop certs because it is useless for user create
certs_empty = validated_data.pop('certs')
user = super().create(validated_data=validated_data)
user.set_password(validated_data["password"])
user.save()
# use certs data to create cert
image_url = self.save_image(certs_data)
_license = validated_data.get('username', None)
TobaccoCert.objects.create(license=_license, license_image=image_url)
return user
In short, you need to add your nested parameters directly in the request parameters. In my example code, it is certs which is vars in your example and then use certs_data = self.initial_data.get('certs') get the parameters you passed in create method.
Another possible way is post your data before your requests:
In postman:
enter image description here
in request:
python - Django Rest Framework writable nested serializer with multiple nested objects - Stack Overflow
In addition, you can try to modify queryDict directly. You can refer to this link and here
Some useful links
django - Need help understanding many and source fields in a serializer - Stack Overflow
python - Django rest framework writeable nested serializer data missing from validated_data - Stack Overflow

is there any way to make a rally ruby rest api call for workspaces return all of them instead of just default?

i'd like to make a call to rally rest api via ruby toolkit to get all workspaces for a subscription, like so:
query = RallyAPI::RallyQuery.new()
query.type = "workspace"
query.fetch = "ObjectID,Name"
query.project_scope_up = false
query.project_scope_down = true
query.order = "Name Asc"
query.query_string = ""
errors = query.validate()
findResults = #connection.find query
but this call apparently only returns the default workspace.
i have semi-successfully been able to navigate to the list of all workspaces when navigating thru the Subscription object, but i would prefer to follow a standard method of going after entity types as illustrated above.
is anyone aware of a way to get all workspaces via a direct query against the workspace type?
WS API calls are workspace scoped. You are correct that the code above will always return only the default workspace, and that workspaces can be accessed via Subscription object. Here is an example:
require 'rally_api'
#Setup custom app information
headers = RallyAPI::CustomHttpHeader.new()
headers.name = "My Utility"
headers.vendor = "Nick M RallyLab"
headers.version = "1.0"
# Connection to Rally
config = {:base_url => "https://rally1.rallydev.com/slm"}
config[:username] = "user#domain.com"
config[:password] = "secret"
config[:workspace] = "W1"
config[:project] = "P1"
config[:headers] = headers #from RallyAPI::CustomHttpHeader.new()
rally = RallyAPI::RallyRestJson.new(config)
query = RallyAPI::RallyQuery.new()
query.type = :subscription
query.fetch = "Name,Workspaces,ObjectID"
results = rally.find(query)
sub = results.first
puts sub["Name"]
workspaces = sub["Workspaces"]
workspaces.each do |w|
puts "Name: #{w["Name"]}, OID: #{w["ObjectID"]}"
end
Whenever a query is intended to look outside of a default workspace, a non-default workspace can be specified. Here is an example of a query on defects outside of the default workspace:
query = RallyAPI::RallyQuery.new()
query.type = :defect
query.fetch = "Name,FormattedID,CreationDate,Owner,UserName"
query.workspace = {"_ref" => "https://rally1.rallydev.com/slm/webservice/1.29/workspace/7777.js" } #optional
query.query_string = "(Owner.UserName = user#company.com)"
I think adding
query.workspace = "null"
will remove the workspace scoping that is applied by default to queries. I haven't tried this with the Ruby client, but I think it should work.

Resources