code
stringlengths
52
7.75k
docs
stringlengths
1
5.85k
def to_bytes(self): ''' Returns serialized bytes object representing all headers/ payloads in this packet''' rawlist = [] i = len(self._headers)-1 while i >= 0: self._headers[i].pre_serialize(b''.join(rawlist), self, i) rawlist.insert(0, self._headers[i].to_bytes()) i -= 1 self._raw = b''.join(rawlist) return self._raf to_bytes(self): ''' Returns serialized bytes object representing all headers/ payloads in this packet''' rawlist = [] i = len(self._headers)-1 while i >= 0: self._headers[i].pre_serialize(b''.join(rawlist), self, i) rawlist.insert(0, self._headers[i].to_bytes()) i -= 1 self._raw = b''.join(rawlist) return self._raw
Returns serialized bytes object representing all headers/ payloads in this packet
def _parse(self, raw, next_cls): ''' Parse a raw bytes object and construct the list of packet header objects (and possible remaining bytes) that are part of this packet. ''' if next_cls is None: from switchyard.lib.packet import Ethernet next_cls = Ethernet self._headers = [] while issubclass(next_cls, PacketHeaderBase): packet_header_obj = next_cls() raw = packet_header_obj.from_bytes(raw) self.add_header(packet_header_obj) next_cls = packet_header_obj.next_header_class() if next_cls is None: break if raw: self.add_header(RawPacketContents(raw)f _parse(self, raw, next_cls): ''' Parse a raw bytes object and construct the list of packet header objects (and possible remaining bytes) that are part of this packet. ''' if next_cls is None: from switchyard.lib.packet import Ethernet next_cls = Ethernet self._headers = [] while issubclass(next_cls, PacketHeaderBase): packet_header_obj = next_cls() raw = packet_header_obj.from_bytes(raw) self.add_header(packet_header_obj) next_cls = packet_header_obj.next_header_class() if next_cls is None: break if raw: self.add_header(RawPacketContents(raw))
Parse a raw bytes object and construct the list of packet header objects (and possible remaining bytes) that are part of this packet.
def add_header(self, ph): ''' Add a PacketHeaderBase derived class object, or a raw bytes object as the next "header" item in this packet. Note that 'header' may be a slight misnomer since the last portion of a packet is considered application payload and not a header per se. ''' if isinstance(ph, bytes): ph = RawPacketContents(ph) if isinstance(ph, PacketHeaderBase): self._headers.append(ph) return self raise Exception("Payload for a packet header must be an object that is a subclass of PacketHeaderBase, or a bytes object."f add_header(self, ph): ''' Add a PacketHeaderBase derived class object, or a raw bytes object as the next "header" item in this packet. Note that 'header' may be a slight misnomer since the last portion of a packet is considered application payload and not a header per se. ''' if isinstance(ph, bytes): ph = RawPacketContents(ph) if isinstance(ph, PacketHeaderBase): self._headers.append(ph) return self raise Exception("Payload for a packet header must be an object that is a subclass of PacketHeaderBase, or a bytes object.")
Add a PacketHeaderBase derived class object, or a raw bytes object as the next "header" item in this packet. Note that 'header' may be a slight misnomer since the last portion of a packet is considered application payload and not a header per se.
def has_header(self, hdrclass): ''' Return True if the packet has a header of the given hdrclass, False otherwise. ''' if isinstance(hdrclass, str): return self.get_header_by_name(hdrclass) is not None return self.get_header(hdrclass) is not Nonf has_header(self, hdrclass): ''' Return True if the packet has a header of the given hdrclass, False otherwise. ''' if isinstance(hdrclass, str): return self.get_header_by_name(hdrclass) is not None return self.get_header(hdrclass) is not None
Return True if the packet has a header of the given hdrclass, False otherwise.
def get_header_by_name(self, hdrname): ''' Return the header object that has the given (string) header class name. Returns None if no such header exists. ''' for hdr in self._headers: if hdr.__class__.__name__ == hdrname: return hdr return Nonf get_header_by_name(self, hdrname): ''' Return the header object that has the given (string) header class name. Returns None if no such header exists. ''' for hdr in self._headers: if hdr.__class__.__name__ == hdrname: return hdr return None
Return the header object that has the given (string) header class name. Returns None if no such header exists.
def get_header(self, hdrclass, returnval=None): ''' Return the first header object that is of class hdrclass, or None if the header class isn't found. ''' if isinstance(hdrclass, str): return self.get_header_by_name(hdrclass) for hdr in self._headers: if isinstance(hdr, hdrclass): return hdr return returnvaf get_header(self, hdrclass, returnval=None): ''' Return the first header object that is of class hdrclass, or None if the header class isn't found. ''' if isinstance(hdrclass, str): return self.get_header_by_name(hdrclass) for hdr in self._headers: if isinstance(hdr, hdrclass): return hdr return returnval
Return the first header object that is of class hdrclass, or None if the header class isn't found.
def get_header_index(self, hdrclass, startidx=0): ''' Return the first index of the header class hdrclass starting at startidx (default=0), or -1 if the header class isn't found in the list of headers. ''' for hdridx in range(startidx, len(self._headers)): if isinstance(self._headers[hdridx], hdrclass): return hdridx return -f get_header_index(self, hdrclass, startidx=0): ''' Return the first index of the header class hdrclass starting at startidx (default=0), or -1 if the header class isn't found in the list of headers. ''' for hdridx in range(startidx, len(self._headers)): if isinstance(self._headers[hdridx], hdrclass): return hdridx return -1
Return the first index of the header class hdrclass starting at startidx (default=0), or -1 if the header class isn't found in the list of headers.
def next_header_class(self): '''Return class of next header, if known.''' if self._next_header_class_key == '': return None key = getattr(self, self._next_header_class_key) rv = self._next_header_map.get(key, None) if rv is None: log_warn("No class exists to handle next header value {}".format(key)) return rf next_header_class(self): '''Return class of next header, if known.''' if self._next_header_class_key == '': return None key = getattr(self, self._next_header_class_key) rv = self._next_header_map.get(key, None) if rv is None: log_warn("No class exists to handle next header value {}".format(key)) return rv
Return class of next header, if known.
def process(self, **context): env = Environment(extensions=['jinja2_time.TimeExtension']) value_template = env.from_string(self.value_template) return value_template.render(**context)
Render value_template of the parameter using context. :param context: Processing context
def post(self, request, hook_id): serializer = UpdateSerializer(data=request.data) if serializer.is_valid(): try: bot = caching.get_or_set(TelegramBot, hook_id) except TelegramBot.DoesNotExist: logger.warning("Hook id %s not associated to an bot" % hook_id) return Response(serializer.errors, status=status.HTTP_404_NOT_FOUND) try: update = self.create_update(serializer, bot) if bot.enabled: logger.debug("Telegram Bot %s attending request %s" % (bot.token, request.data)) handle_update.delay(update.id, bot.id) else: logger.error("Update %s ignored by disabled bot %s" % (update, bot.token)) except OnlyTextMessages: logger.warning("Not text message %s for bot %s" % (request.data, hook_id)) return Response(status=status.HTTP_200_OK) except: exc_info = sys.exc_info() traceback.print_exception(*exc_info) logger.error("Error processing %s for bot %s" % (request.data, hook_id)) return Response(serializer.errors, status=status.HTTP_500_INTERNAL_SERVER_ERROR) else: return Response(serializer.data, status=status.HTTP_200_OK) logger.error("Validation error: %s from message %s" % (serializer.errors, request.data)) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Process Telegram webhook. 1. Serialize Telegram message 2. Get an enabled Telegram bot 3. Create :class:`Update <permabots.models.telegram_api.Update>` 5. Delay processing to a task 6. Response provider
def get(self, request, format=None): bots = Bot.objects.filter(owner=request.user) serializer = BotSerializer(bots, many=True) return Response(serializer.data)
Get list of bots --- serializer: BotSerializer responseMessages: - code: 401 message: Not authenticated
def post(self, request, format=None): serializer = BotSerializer(data=request.data) if serializer.is_valid(): bot = Bot.objects.create(owner=request.user, name=serializer.data['name']) return Response(BotSerializer(bot).data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Add a new bot --- serializer: BotSerializer responseMessages: - code: 401 message: Not authenticated - code: 400 message: Not valid request
def get(self, request, id, format=None): bot = self.get_bot(id, request.user) serializer = BotSerializer(bot) return Response(serializer.data)
Get bot by id --- serializer: BotSerializer responseMessages: - code: 401 message: Not authenticated
def put(self, request, id, format=None): bot = self.get_bot(id, request.user) serializer = BotUpdateSerializer(bot, data=request.data) if serializer.is_valid(): try: bot = serializer.save() except: return Response(status=status.HTTP_400_BAD_REQUEST) else: return Response(BotSerializer(bot).data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Update an existing bot --- serializer: BotUpdateSerializer responseMessages: - code: 401 message: Not authenticated - code: 400 message: Not valid request
def delete(self, request, id, format=None): bot = self.get_bot(id, request.user) bot.delete() return Response(status=status.HTTP_204_NO_CONTENT)
Delete an existing bot --- responseMessages: - code: 401 message: Not authenticated
def get(self, request, bot_id, format=None): return super(TelegramBotList, self).get(request, bot_id, format)
Get list of Telegram bots --- serializer: TelegramBotSerializer responseMessages: - code: 401 message: Not authenticated
def post(self, request, bot_id, format=None): try: return super(TelegramBotList, self).post(request, bot_id, format) except: return Response({"error": 'Telegram Error. Check Telegram token or try later.'}, status=status.HTTP_400_BAD_REQUEST)
Add TelegramBot --- serializer: TelegramBotSerializer responseMessages: - code: 401 message: Not authenticated - code: 400 message: Not valid request
def get(self, request, bot_id, id, format=None): return super(TelegramBotDetail, self).get(request, bot_id, id, format)
Get TelegramBot by id --- serializer: TelegramBotSerializer responseMessages: - code: 401 message: Not authenticated
def put(self, request, bot_id, id, format=None): return super(TelegramBotDetail, self).put(request, bot_id, id, format)
Update existing TelegramBot --- serializer: TelegramBotUpdateSerializer responseMessages: - code: 401 message: Not authenticated - code: 400 message: Not valid request
def delete(self, request, bot_id, id, format=None): return super(TelegramBotDetail, self).delete(request, bot_id, id, format)
Delete existing Telegram Bot --- responseMessages: - code: 401 message: Not authenticated
def get(self, request, bot_id, format=None): return super(KikBotList, self).get(request, bot_id, format)
Get list of Kik bots --- serializer: KikBotSerializer responseMessages: - code: 401 message: Not authenticated
def get(self, request, bot_id, id, format=None): return super(KikBotDetail, self).get(request, bot_id, id, format)
Get KikBot by id --- serializer: KikBotSerializer responseMessages: - code: 401 message: Not authenticated
def put(self, request, bot_id, id, format=None): return super(KikBotDetail, self).put(request, bot_id, id, format)
Update existing KikBot --- serializer: KikBotUpdateSerializer responseMessages: - code: 401 message: Not authenticated - code: 400 message: Not valid request
def delete(self, request, bot_id, id, format=None): return super(KikBotDetail, self).delete(request, bot_id, id, format)
Delete existing Kik Bot --- responseMessages: - code: 401 message: Not authenticated
def get(self, request, bot_id, format=None): return super(MessengerBotList, self).get(request, bot_id, format)
Get list of Messenger bots --- serializer: MessengerBotSerializer responseMessages: - code: 401 message: Not authenticated
def get(self, request, bot_id, id, format=None): return super(MessengerBotDetail, self).get(request, bot_id, id, format)
Get MessengerBot by id --- serializer: MessengerBotSerializer responseMessages: - code: 401 message: Not authenticated
def put(self, request, bot_id, id, format=None): return super(MessengerBotDetail, self).put(request, bot_id, id, format)
Update existing MessengerBot --- serializer: MessengerBotUpdateSerializer responseMessages: - code: 401 message: Not authenticated - code: 400 message: Not valid request
def delete(self, request, bot_id, id, format=None): return super(MessengerBotDetail, self).delete(request, bot_id, id, format)
Delete existing Messenger Bot --- responseMessages: - code: 401 message: Not authenticated
def get(self, request, bot_id, format=None): return super(StateList, self).get(request, bot_id, format)
Get list of states --- serializer: StateSerializer responseMessages: - code: 401 message: Not authenticated
def post(self, request, bot_id, format=None): return super(StateList, self).post(request, bot_id, format)
Add a new state --- serializer: StateSerializer responseMessages: - code: 401 message: Not authenticated - code: 400 message: Not valid request
def get(self, request, bot_id, id, format=None): return super(StateDetail, self).get(request, bot_id, id, format)
Get state by id --- serializer: StateSerializer responseMessages: - code: 401 message: Not authenticated
def put(self, request, bot_id, id, format=None): return super(StateDetail, self).put(request, bot_id, id, format)
Update existing state --- serializer: StateSerializer responseMessages: - code: 401 message: Not authenticated - code: 400 message: Not valid request
def delete(self, request, bot_id, id, format=None): return super(StateDetail, self).delete(request, bot_id, id, format)
Delete existing state --- responseMessages: - code: 401 message: Not authenticated
def get(self, request, bot_id, format=None): return super(TelegramChatStateList, self).get(request, bot_id, format)
Get list of chat state --- serializer: TelegramChatStateSerializer responseMessages: - code: 401 message: Not authenticated
def post(self, request, bot_id, format=None): return super(TelegramChatStateList, self).post(request, bot_id, format)
Add a new chat state --- serializer: TelegramChatStateSerializer responseMessages: - code: 401 message: Not authenticated - code: 400 message: Not valid request
def get(self, request, bot_id, id, format=None): return super(TelegramChatStateDetail, self).get(request, bot_id, id, format)
Get Telegram chat state by id --- serializer: TelegramChatStateSerializer responseMessages: - code: 401 message: Not authenticated
def put(self, request, bot_id, id, format=None): return super(TelegramChatStateDetail, self).put(request, bot_id, id, format)
Update existing Telegram chat state --- serializer: TelegramChatStateSerializer responseMessages: - code: 401 message: Not authenticated - code: 400 message: Not valid request
def delete(self, request, bot_id, id, format=None): return super(TelegramChatStateDetail, self).delete(request, bot_id, id, format)
Delete existing Kik chat state --- responseMessages: - code: 401 message: Not authenticated
def get(self, request, bot_id, format=None): return super(KikChatStateList, self).get(request, bot_id, format)
Get list of chat state --- serializer: KikChatStateSerializer responseMessages: - code: 401 message: Not authenticated
def post(self, request, bot_id, format=None): return super(KikChatStateList, self).post(request, bot_id, format)
Add a new chat state --- serializer: KikChatStateSerializer responseMessages: - code: 401 message: Not authenticated - code: 400 message: Not valid request
def get(self, request, bot_id, id, format=None): return super(KikChatStateDetail, self).get(request, bot_id, id, format)
Get Kik chat state by id --- serializer: KikChatStateSerializer responseMessages: - code: 401 message: Not authenticated
def put(self, request, bot_id, id, format=None): return super(KikChatStateDetail, self).put(request, bot_id, id, format)
Update existing Kik chat state --- serializer: KikChatStateSerializer responseMessages: - code: 401 message: Not authenticated - code: 400 message: Not valid request
def delete(self, request, bot_id, id, format=None): return super(KikChatStateDetail, self).delete(request, bot_id, id, format)
Delete existing Kik chat state --- responseMessages: - code: 401 message: Not authenticated
def get(self, request, bot_id, format=None): return super(MessengerChatStateList, self).get(request, bot_id, format)
Get list of chat state --- serializer: MessengerChatStateSerializer responseMessages: - code: 401 message: Not authenticated
def post(self, request, bot_id, format=None): return super(MessengerChatStateList, self).post(request, bot_id, format)
Add a new chat state --- serializer: MessengerChatStateSerializer responseMessages: - code: 401 message: Not authenticated - code: 400 message: Not valid request
def get(self, request, bot_id, id, format=None): return super(MessengerChatStateDetail, self).get(request, bot_id, id, format)
Get Messenger chat state by id --- serializer: MessengerChatStateSerializer responseMessages: - code: 401 message: Not authenticated
def put(self, request, bot_id, id, format=None): return super(MessengerChatStateDetail, self).put(request, bot_id, id, format)
Update existing Messenger chat state --- serializer: MessengerChatStateSerializer responseMessages: - code: 401 message: Not authenticated - code: 400 message: Not valid request
def delete(self, request, bot_id, id, format=None): return super(MessengerChatStateDetail, self).delete(request, bot_id, id, format)
Delete existing Messenger chat state --- responseMessages: - code: 401 message: Not authenticated
def get(self, request, bot_id, format=None): return super(HandlerList, self).get(request, bot_id, format)
Get list of handlers --- serializer: HandlerSerializer responseMessages: - code: 401 message: Not authenticated
def post(self, request, bot_id, format=None): return super(HandlerList, self).post(request, bot_id, format)
Add a new handler --- serializer: HandlerSerializer responseMessages: - code: 401 message: Not authenticated - code: 400 message: Not valid request
def get(self, request, bot_id, id, format=None): return super(HandlerDetail, self).get(request, bot_id, id, format)
Get handler by id --- serializer: HandlerSerializer responseMessages: - code: 401 message: Not authenticated
def put(self, request, bot_id, id, format=None): return super(HandlerDetail, self).put(request, bot_id, id, format)
Update existing handler --- serializer: HandlerUpdateSerializer responseMessages: - code: 401 message: Not authenticated - code: 400 message: Not valid request
def delete(self, request, bot_id, id, format=None): return super(HandlerDetail, self).delete(request, bot_id, id, format)
Delete existing handler --- responseMessages: - code: 401 message: Not authenticated
def get(self, request, bot_id, id, format=None): return super(UrlParameterList, self).get(request, bot_id, id, format)
Get list of url parameters of a handler --- serializer: AbsParamSerializer responseMessages: - code: 401 message: Not authenticated
def post(self, request, bot_id, id, format=None): return super(UrlParameterList, self).post(request, bot_id, id, format)
Add a new url parameter to a handler --- serializer: AbsParamSerializer responseMessages: - code: 401 message: Not authenticated - code: 400 message: Not valid request
def get(self, request, bot_id, id, format=None): return super(HeaderParameterList, self).get(request, bot_id, id, format)
Get list of header parameters of a handler --- serializer: AbsParamSerializer responseMessages: - code: 401 message: Not authenticated
def post(self, request, bot_id, id, format=None): return super(HeaderParameterList, self).post(request, bot_id, id, format)
Add a new header parameter to a handler --- serializer: AbsParamSerializer responseMessages: - code: 401 message: Not authenticated - code: 400 message: Not valid request
def get(self, request, bot_id, handler_id, id, format=None): return super(UrlParameterDetail, self).get(request, bot_id, handler_id, id, format)
Get url parameter by id --- serializer: AbsParamSerializer responseMessages: - code: 401 message: Not authenticated
def get(self, request, bot_id, id, format=None): return super(SourceStateList, self).get(request, bot_id, id, format)
Get list of source state of a handler --- serializer: StateSerializer responseMessages: - code: 401 message: Not authenticated
def post(self, request, bot_id, id, format=None): return super(SourceStateList, self).post(request, bot_id, id, format)
Add a new source state to a handler --- serializer: StateSerializer responseMessages: - code: 401 message: Not authenticated - code: 400 message: Not valid request
def get(self, request, hook_id): try: bot = caching.get_or_set(MessengerBot, hook_id) except MessengerBot.DoesNotExist: logger.warning("Hook id %s not associated to a bot" % hook_id) return Response(status=status.HTTP_404_NOT_FOUND) if request.query_params.get('hub.verify_token') == str(bot.id): return Response(int(request.query_params.get('hub.challenge'))) return Response('Error, wrong validation token')
Verify token when configuring webhook from facebook dev. MessengerBot.id is used for verification
def post(self, request, hook_id): try: bot = caching.get_or_set(MessengerBot, hook_id) except MessengerBot.DoesNotExist: logger.warning("Hook id %s not associated to a bot" % hook_id) return Response(status=status.HTTP_404_NOT_FOUND) logger.debug("Messenger Bot %s attending request %s" % (bot, request.data)) webhook = Webhook.from_json(request.data) for webhook_entry in webhook.entries: for webhook_message in webhook_entry.messaging: try: if webhook_message.is_delivery: raise OnlyTextMessages message = self.create_message(webhook_message, bot) if bot.enabled: logger.debug("Messenger Bot %s attending request %s" % (bot, message)) handle_messenger_message.delay(message.id, bot.id) else: logger.error("Message %s ignored by disabled bot %s" % (message, bot)) except OnlyTextMessages: logger.warning("Not text message %s for bot %s" % (message, hook_id)) except: exc_info = sys.exc_info() traceback.print_exception(*exc_info) logger.error("Error processing %s for bot %s" % (webhook_message, hook_id)) return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR) return Response(status=status.HTTP_200_OK)
Process Messenger webhook. 1. Get an enabled Messenger bot 3. For each message serialize 4. For each message create :class:`MessengerMessage <permabots.models.messenger_api.MessengerMessage>` 5. Delay processing of each message to a task 6. Response provider
def get(self, request, bot_id, format=None): return super(HookList, self).get(request, bot_id, format)
Get list of hooks --- serializer: HookSerializer responseMessages: - code: 401 message: Not authenticated
def post(self, request, bot_id, format=None): return super(HookList, self).post(request, bot_id, format)
Add a new hook --- serializer: HookSerializer responseMessages: - code: 401 message: Not authenticated - code: 400 message: Not valid request
def get(self, request, bot_id, id, format=None): return super(HookDetail, self).get(request, bot_id, id, format)
Get hook by id --- serializer: HookSerializer responseMessages: - code: 401 message: Not authenticated
def put(self, request, bot_id, id, format=None): return super(HookDetail, self).put(request, bot_id, id, format)
Update existing hook --- serializer: HookUpdateSerializer responseMessages: - code: 401 message: Not authenticated - code: 400 message: Not valid request
def delete(self, request, bot_id, id, format=None): return super(HookDetail, self).delete(request, bot_id, id, format)
Delete existing hook --- responseMessages: - code: 401 message: Not authenticated
def get(self, request, bot_id, id, format=None): return super(TelegramRecipientList, self).get(request, bot_id, id, format)
Get list of telegram recipients of a hook --- serializer: TelegramRecipientSerializer responseMessages: - code: 401 message: Not authenticated
def post(self, request, bot_id, id, format=None): return super(TelegramRecipientList, self).post(request, bot_id, id, format)
Add a new telegram recipient to a handler --- serializer: TelegramRecipientSerializer responseMessages: - code: 401 message: Not authenticated - code: 400 message: Not valid request
def get(self, request, bot_id, hook_id, id, format=None): bot = self.get_bot(bot_id, request.user) hook = self.get_hook(hook_id, bot, request.user) recipient = self.get_recipient(id, hook, request.user) serializer = self.serializer(recipient) return Response(serializer.data)
Get recipient by id --- serializer: TelegramRecipientSerializer responseMessages: - code: 401 message: Not authenticated
def put(self, request, bot_id, hook_id, id, format=None): bot = self.get_bot(bot_id, request.user) hook = self.get_hook(hook_id, bot, request.user) recipient = self.get_recipient(id, hook, request.user) serializer = self.serializer(recipient, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Update existing telegram recipient --- serializer: TelegramRecipientSerializer responseMessages: - code: 401 message: Not authenticated - code: 400 message: Not valid request
def delete(self, request, bot_id, hook_id, id, format=None): bot = self.get_bot(bot_id, request.user) hook = self.get_hook(hook_id, bot, request.user) recipient = self.get_recipient(id, hook, request.user) recipient.delete() return Response(status=status.HTTP_204_NO_CONTENT)
Delete an existing telegram recipient --- responseMessages: - code: 401 message: Not authenticated
def get(self, request, bot_id, id, format=None): return super(KikRecipientList, self).get(request, bot_id, id, format)
Get list of kik recipients of a hook --- serializer: KikRecipientSerializer responseMessages: - code: 401 message: Not authenticated
def post(self, request, bot_id, id, format=None): return super(KikRecipientList, self).post(request, bot_id, id, format)
Add a new kik recipient to a handler --- serializer: KikRecipientSerializer responseMessages: - code: 401 message: Not authenticated - code: 400 message: Not valid request
def get(self, request, bot_id, id, format=None): return super(MessengerRecipientList, self).get(request, bot_id, id, format)
Get list of Messenger recipients of a hook --- serializer: MessengerRecipientSerializer responseMessages: - code: 401 message: Not authenticated
def post(self, request, bot_id, id, format=None): return super(MessengerRecipientList, self).post(request, bot_id, id, format)
Add a new messenger recipient to a handler --- serializer: MessengerRecipientSerializer responseMessages: - code: 401 message: Not authenticated - code: 400 message: Not valid request
def get(self, request, bot_id, format=None): return super(EnvironmentVarList, self).get(request, bot_id, format)
Get list of environment variables --- serializer: EnvironmentVarSerializer responseMessages: - code: 401 message: Not authenticated
def post(self, request, bot_id, format=None): return super(EnvironmentVarList, self).post(request, bot_id, format)
Add a new environment variable --- serializer: EnvironmentVarSerializer responseMessages: - code: 401 message: Not authenticated - code: 400 message: Not valid request
def get(self, request, bot_id, id, format=None): return super(EnvironmentVarDetail, self).get(request, bot_id, id, format)
Get environment variable by id --- serializer: EnvironmentVarSerializer responseMessages: - code: 401 message: Not authenticated
def put(self, request, bot_id, id, format=None): return super(EnvironmentVarDetail, self).put(request, bot_id, id, format)
Update existing environment variable --- serializer: EnvironmentVarSerializer responseMessages: - code: 401 message: Not authenticated - code: 400 message: Not valid request
def delete(self, request, bot_id, id, format=None): return super(EnvironmentVarDetail, self).delete(request, bot_id, id, format)
Delete existing environment variable --- responseMessages: - code: 401 message: Not authenticated
def post(self, request, key): try: hook = Hook.objects.get(key=key, enabled=True) except Hook.DoesNotExist: msg = _("Key %s not associated to an enabled hook or bot") % key logger.warning(msg) return Response(msg, status=status.HTTP_404_NOT_FOUND) if hook.bot.owner != request.user: raise exceptions.AuthenticationFailed() try: parsed_data = request.data logger.debug("Hook %s attending request %s" % (hook, parsed_data)) handle_hook.delay(hook.id, parsed_data) except ParseError as e: return Response(str(e), status=status.HTTP_400_BAD_REQUEST) except: exc_info = sys.exc_info() traceback.print_exception(*exc_info) msg = _("Error processing %s for key %s") % (request.data, key) logger.error(msg) return Response(msg, status=status.HTTP_500_INTERNAL_SERVER_ERROR) else: return Response(status=status.HTTP_200_OK)
Process notitication hooks: 1. Obtain Hook 2. Check Auth 3. Delay processing to a task 4. Respond requester
def _format_value(self, value): # Use renamed format_name() for Django versions >= 1.10. if hasattr(self, 'format_value'): return super(DateTimePicker, self).format_value(value) # Use old _format_name() for Django versions < 1.10. else: return super(DateTimePicker, self)._format_value(value)
This function name was changed in Django 1.10 and removed in 2.0.
def authorize_url(self, client_id, redirect_uri, scope, state=None): params = [ ('client_id', client_id), ('redirect_uri', redirect_uri), ('scope', scope) ] if state: params.append(('state', state)) return "%s?%s" % (CreateSend.oauth_uri, urlencode(params))
Get the authorization URL for your application, given the application's client_id, redirect_uri, scope, and optional state data.
def exchange_token(self, client_id, client_secret, redirect_uri, code): params = [ ('grant_type', 'authorization_code'), ('client_id', client_id), ('client_secret', client_secret), ('redirect_uri', redirect_uri), ('code', code), ] response = self._post('', urlencode(params), CreateSend.oauth_token_uri, "application/x-www-form-urlencoded") access_token, expires_in, refresh_token = None, None, None r = json_to_py(response) if hasattr(r, 'error') and hasattr(r, 'error_description'): err = "Error exchanging code for access token: " err += "%s - %s" % (r.error, r.error_description) raise Exception(err) access_token, expires_in, refresh_token = r.access_token, r.expires_in, r.refresh_token return [access_token, expires_in, refresh_token]
Exchange a provided OAuth code for an OAuth access token, 'expires in' value and refresh token.
def refresh_token(self): if (not self.auth_details or not 'refresh_token' in self.auth_details or not self.auth_details['refresh_token']): raise Exception( "auth_details['refresh_token'] does not contain a refresh token.") refresh_token = self.auth_details['refresh_token'] params = [ ('grant_type', 'refresh_token'), ('refresh_token', refresh_token) ] response = self._post('', urlencode(params), CreateSend.oauth_token_uri, "application/x-www-form-urlencoded") new_access_token, new_expires_in, new_refresh_token = None, None, None r = json_to_py(response) new_access_token, new_expires_in, new_refresh_token = r.access_token, r.expires_in, r.refresh_token self.auth({ 'access_token': new_access_token, 'refresh_token': new_refresh_token}) return [new_access_token, new_expires_in, new_refresh_token]
Refresh an OAuth token given a refresh token.
def stub_request(self, expected_url, filename, status=None, body=None): self.fake_web = True self.faker = get_faker(expected_url, filename, status, body)
Stub a web request for testing.
def external_session_url(self, email, chrome, url, integrator_id, client_id): body = { "Email": email, "Chrome": chrome, "Url": url, "IntegratorID": integrator_id, "ClientID": client_id} response = self._put('/externalsession.json', json.dumps(body)) return json_to_py(response)
Get a URL which initiates a new external session for the user with the given email. Full details: http://www.campaignmonitor.com/api/account/#single_sign_on :param email: String The representing the email address of the Campaign Monitor user for whom the login session should be created. :param chrome: String representing which 'chrome' to display - Must be either "all", "tabs", or "none". :param url: String representing the URL to display once logged in. e.g. "/subscribers/" :param integrator_id: String representing the Integrator ID. You need to contact Campaign Monitor support to get an Integrator ID. :param client_id: String representing the Client ID of the client which should be active once logged in to the Campaign Monitor account. :returns Object containing a single field SessionUrl which represents the URL to initiate the external Campaign Monitor session.
def get(self, client_id=None, email_address=None): params = {"email": email_address or self.email_address} response = self._get("/clients/%s/people.json" % (client_id or self.client_id), params=params) return json_to_py(response)
Gets a person by client ID and email address.
def add(self, client_id, email_address, name, access_level, password): body = { "EmailAddress": email_address, "Name": name, "AccessLevel": access_level, "Password": password} response = self._post("/clients/%s/people.json" % client_id, json.dumps(body)) return json_to_py(response)
Adds a person to a client. Password is optional and if not supplied, an invitation will be emailed to the person
def update(self, new_email_address, name, access_level, password=None): params = {"email": self.email_address} body = { "EmailAddress": new_email_address, "Name": name, "AccessLevel": access_level, "Password": password} response = self._put("/clients/%s/people.json" % self.client_id, body=json.dumps(body), params=params) # Update self.email_address, so this object can continue to be used # reliably self.email_address = new_email_address
Updates the details for a person. Password is optional and is only updated if supplied.
def create(self, client_id, subject, name, from_name, from_email, reply_to, html_url, text_url, list_ids, segment_ids): body = { "Subject": subject, "Name": name, "FromName": from_name, "FromEmail": from_email, "ReplyTo": reply_to, "HtmlUrl": html_url, "TextUrl": text_url, "ListIDs": list_ids, "SegmentIDs": segment_ids} response = self._post("/campaigns/%s.json" % client_id, json.dumps(body)) self.campaign_id = json_to_py(response) return self.campaign_id
Creates a new campaign for a client. :param client_id: String representing the ID of the client for whom the campaign will be created. :param subject: String representing the subject of the campaign. :param name: String representing the name of the campaign. :param from_name: String representing the from name for the campaign. :param from_email: String representing the from address for the campaign. :param reply_to: String representing the reply-to address for the campaign. :param html_url: String representing the URL for the campaign HTML content. :param text_url: String representing the URL for the campaign text content. Note that text_url is optional and if None or an empty string, text content will be automatically generated from the HTML content. :param list_ids: Array of Strings representing the IDs of the lists to which the campaign will be sent. :param segment_ids: Array of Strings representing the IDs of the segments to which the campaign will be sent. :returns String representing the ID of the newly created campaign.
def create_from_template(self, client_id, subject, name, from_name, from_email, reply_to, list_ids, segment_ids, template_id, template_content): body = { "Subject": subject, "Name": name, "FromName": from_name, "FromEmail": from_email, "ReplyTo": reply_to, "ListIDs": list_ids, "SegmentIDs": segment_ids, "TemplateID": template_id, "TemplateContent": template_content} response = self._post("/campaigns/%s/fromtemplate.json" % client_id, json.dumps(body)) self.campaign_id = json_to_py(response) return self.campaign_id
Creates a new campaign for a client, from a template. :param client_id: String representing the ID of the client for whom the campaign will be created. :param subject: String representing the subject of the campaign. :param name: String representing the name of the campaign. :param from_name: String representing the from name for the campaign. :param from_email: String representing the from address for the campaign. :param reply_to: String representing the reply-to address for the campaign. :param list_ids: Array of Strings representing the IDs of the lists to which the campaign will be sent. :param segment_ids: Array of Strings representing the IDs of the segments to which the campaign will be sent. :param template_id: String representing the ID of the template on which the campaign will be based. :param template_content: Hash representing the content to be used for the editable areas of the template. See documentation at campaignmonitor.com/api/campaigns/#creating_a_campaign_from_template for full details of template content format. :returns String representing the ID of the newly created campaign.
def send_preview(self, recipients, personalize="fallback"): body = { "PreviewRecipients": [recipients] if isinstance(recipients, str) else recipients, "Personalize": personalize} response = self._post(self.uri_for("sendpreview"), json.dumps(body))
Sends a preview of this campaign.
def send(self, confirmation_email, send_date="immediately"): body = { "ConfirmationEmail": confirmation_email, "SendDate": send_date} response = self._post(self.uri_for("send"), json.dumps(body))
Sends this campaign.
def opens(self, date="", page=1, page_size=1000, order_field="date", order_direction="asc"): params = { "date": date, "page": page, "pagesize": page_size, "orderfield": order_field, "orderdirection": order_direction} response = self._get(self.uri_for("opens"), params=params) return json_to_py(response)
Retrieves the opens for this campaign.
def create(self, company, timezone, country): body = { "CompanyName": company, "TimeZone": timezone, "Country": country} response = self._post("/clients.json", json.dumps(body)) self.client_id = json_to_py(response) return self.client_id
Creates a client.
def lists_for_email(self, email_address): params = {"email": email_address} response = self._get(self.uri_for("listsforemail"), params=params) return json_to_py(response)
Gets the lists across a client to which a subscriber with a particular email address belongs.
def suppressionlist(self, page=1, page_size=1000, order_field="email", order_direction="asc"): params = { "page": page, "pagesize": page_size, "orderfield": order_field, "orderdirection": order_direction} response = self._get(self.uri_for("suppressionlist"), params=params) return json_to_py(response)
Gets this client's suppression list.
def suppress(self, email): body = { "EmailAddresses": [email] if isinstance(email, str) else email} response = self._post(self.uri_for("suppress"), json.dumps(body))
Adds email addresses to a client's suppression list