Skip to content

pylint and black changes to samples #427

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 12, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 14 additions & 11 deletions samples/01.console-echo/adapter/console_adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ async def send_activities(self, context: TurnContext, activities: List[Activity]
raise TypeError(
"ConsoleAdapter.send_activities(): `context` argument cannot be None."
)
if type(activities) != list:
if not isinstance(activities, list):
raise TypeError(
"ConsoleAdapter.send_activities(): `activities` argument must be a list."
)
Expand All @@ -130,24 +130,27 @@ async def next_activity(i: int):

if i < len(activities):
responses.append(ResourceResponse())
a = activities[i]
activity = activities[i]

if a.type == "delay":
await asyncio.sleep(a.delay)
if activity.type == "delay":
await asyncio.sleep(activity.delay)
await next_activity(i + 1)
elif a.type == ActivityTypes.message:
if a.attachments is not None and len(a.attachments) > 0:
elif activity.type == ActivityTypes.message:
if (
activity.attachments is not None
and len(activity.attachments) > 0
):
append = (
"(1 attachment)"
if len(a.attachments) == 1
else f"({len(a.attachments)} attachments)"
if len(activity.attachments) == 1
else f"({len(activity.attachments)} attachments)"
)
print(f"{a.text} {append}")
print(f"{activity.text} {append}")
else:
print(a.text)
print(activity.text)
await next_activity(i + 1)
else:
print(f"[{a.type}]")
print(f"[{activity.type}]")
await next_activity(i + 1)
else:
return responses
Expand Down
14 changes: 6 additions & 8 deletions samples/01.console-echo/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,24 @@
# Licensed under the MIT License.

import asyncio
from botbuilder.core import TurnContext, ConversationState, UserState, MemoryStorage
from botbuilder.schema import ActivityTypes

from adapter import ConsoleAdapter
from bot import EchoBot

# Create adapter
adapter = ConsoleAdapter()
bot = EchoBot()
ADAPTER = ConsoleAdapter()
BOT = EchoBot()

loop = asyncio.get_event_loop()
LOOP = asyncio.get_event_loop()

if __name__ == "__main__":
try:
# Greet user
print("Hi... I'm an echobot. Whatever you say I'll echo back.")

loop.run_until_complete(adapter.process_activity(bot.on_turn))
LOOP.run_until_complete(ADAPTER.process_activity(BOT.on_turn))
except KeyboardInterrupt:
pass
finally:
loop.stop()
loop.close()
LOOP.stop()
LOOP.close()
5 changes: 2 additions & 3 deletions samples/02.echo-bot/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import asyncio
import sys
from datetime import datetime
from types import MethodType

from flask import Flask, request, Response
from botbuilder.core import BotFrameworkAdapterSettings, TurnContext, BotFrameworkAdapter
Expand All @@ -24,7 +23,7 @@


# Catch-all for errors.
async def on_error(self, context: TurnContext, error: Exception):
async def on_error(context: TurnContext, error: Exception):
# This check writes out errors to console log .vs. app insights.
# NOTE: In production environment, you should consider logging this to Azure
# application insights.
Expand All @@ -47,7 +46,7 @@ async def on_error(self, context: TurnContext, error: Exception):
# Send a trace activity, which will be displayed in Bot Framework Emulator
await context.send_activity(trace_activity)

ADAPTER.on_turn_error = MethodType(on_error, ADAPTER)
ADAPTER.on_turn_error = on_error

# Create the Bot
BOT = EchoBot()
Expand Down
14 changes: 8 additions & 6 deletions samples/03.welcome-user/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import asyncio
import sys
from datetime import datetime
from types import MethodType

from flask import Flask, request, Response
from botbuilder.core import (
Expand All @@ -30,30 +29,33 @@


# Catch-all for errors.
async def on_error(self, context: TurnContext, error: Exception):
async def on_error(context: TurnContext, error: Exception):
# This check writes out errors to console log .vs. app insights.
# NOTE: In production environment, you should consider logging this to Azure
# application insights.
print(f"\n [on_turn_error] unhandled error: {error}", file=sys.stderr)

# Send a message to the user
await context.send_activity("The bot encountered an error or bug.")
await context.send_activity("To continue to run this bot, please fix the bot source code.")
await context.send_activity(
"To continue to run this bot, please fix the bot source code."
)
# Send a trace activity if we're talking to the Bot Framework Emulator
if context.activity.channel_id == 'emulator':
if context.activity.channel_id == "emulator":
# Create a trace activity that contains the error object
trace_activity = Activity(
label="TurnError",
name="on_turn_error Trace",
timestamp=datetime.utcnow(),
type=ActivityTypes.trace,
value=f"{error}",
value_type="https://www.botframework.com/schemas/error"
value_type="https://www.botframework.com/schemas/error",
)
# Send a trace activity, which will be displayed in Bot Framework Emulator
await context.send_activity(trace_activity)

ADAPTER.on_turn_error = MethodType(on_error, ADAPTER)

ADAPTER.on_turn_error = on_error

# Create MemoryStorage, UserState
MEMORY = MemoryStorage()
Expand Down
104 changes: 57 additions & 47 deletions samples/03.welcome-user/bots/welcome_user_bot.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,20 @@
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.

from botbuilder.core import ActivityHandler, TurnContext, UserState, CardFactory, MessageFactory
from botbuilder.schema import ChannelAccount, HeroCard, CardImage, CardAction, ActionTypes
from botbuilder.core import (
ActivityHandler,
TurnContext,
UserState,
CardFactory,
MessageFactory,
)
from botbuilder.schema import (
ChannelAccount,
HeroCard,
CardImage,
CardAction,
ActionTypes,
)

from data_models import WelcomeUserState

Expand All @@ -18,76 +30,76 @@ def __init__(self, user_state: UserState):

self.user_state_accessor = self.user_state.create_property("WelcomeUserState")

self.WELCOME_MESSAGE = """This is a simple Welcome Bot sample. This bot will introduce you
to welcoming and greeting users. You can say 'intro' to see the
introduction card. If you are running this bot in the Bot Framework
Emulator, press the 'Restart Conversation' button to simulate user joining
self.WELCOME_MESSAGE = """This is a simple Welcome Bot sample. This bot will introduce you
to welcoming and greeting users. You can say 'intro' to see the
introduction card. If you are running this bot in the Bot Framework
Emulator, press the 'Restart Conversation' button to simulate user joining
a bot or a channel"""

async def on_turn(self, turn_context: TurnContext):
await super().on_turn(turn_context)

# save changes to WelcomeUserState after each turn
await self.user_state.save_changes(turn_context)

"""
Greet when users are added to the conversation.
Note that all channels do not send the conversation update activity.
If you find that this bot works in the emulator, but does not in
another channel the reason is most likely that the channel does not
send this activity.
"""

async def on_members_added_activity(
self, members_added: [ChannelAccount], turn_context: TurnContext
):
"""
Greet when users are added to the conversation.
Note that all channels do not send the conversation update activity.
If you find that this bot works in the emulator, but does not in
another channel the reason is most likely that the channel does not
send this activity.
"""
for member in members_added:
if member.id != turn_context.activity.recipient.id:
await turn_context.send_activity(
f"Hi there { member.name }. " + self.WELCOME_MESSAGE
)

await turn_context.send_activity("""You are seeing this message because the bot received at least one
'ConversationUpdate' event, indicating you (and possibly others)
joined the conversation. If you are using the emulator, pressing
the 'Start Over' button to trigger this event again. The specifics
of the 'ConversationUpdate' event depends on the channel. You can
await turn_context.send_activity(
"""You are seeing this message because the bot received at least one
'ConversationUpdate' event, indicating you (and possibly others)
joined the conversation. If you are using the emulator, pressing
the 'Start Over' button to trigger this event again. The specifics
of the 'ConversationUpdate' event depends on the channel. You can
read more information at: https://aka.ms/about-botframework-welcome-user"""
)

await turn_context.send_activity("""It is a good pattern to use this event to send general greeting
to user, explaining what your bot can do. In this example, the bot
await turn_context.send_activity(
"""It is a good pattern to use this event to send general greeting
to user, explaining what your bot can do. In this example, the bot
handles 'hello', 'hi', 'help' and 'intro'. Try it now, type 'hi'"""
)

"""
Respond to messages sent from the user.
"""

async def on_message_activity(self, turn_context: TurnContext):
"""
Respond to messages sent from the user.
"""
# Get the state properties from the turn context.
welcome_user_state = await self.user_state_accessor.get(turn_context, WelcomeUserState)
welcome_user_state = await self.user_state_accessor.get(
turn_context, WelcomeUserState
)

if not welcome_user_state.did_welcome_user:
welcome_user_state.did_welcome_user = True

await turn_context.send_activity(
"You are seeing this message because this was your first message ever to this bot."
)
)

name = turn_context.activity.from_property.name
await turn_context.send_activity(
f"It is a good practice to welcome the user and provide personal greeting. For example: Welcome { name }"
f"It is a good practice to welcome the user and provide personal greeting. For example: Welcome {name}"
)

else:
# This example hardcodes specific utterances. You should use LUIS or QnA for more advance language
# understanding.
text = turn_context.activity.text.lower()
if text in ("hello", "hi"):
await turn_context.send_activity(
f"You said { text }"
)
await turn_context.send_activity(f"You said { text }")
elif text in ("intro", "help"):
await self.__send_intro_card(turn_context)
else:
Expand All @@ -97,37 +109,35 @@ async def __send_intro_card(self, turn_context: TurnContext):
card = HeroCard(
title="Welcome to Bot Framework!",
text="Welcome to Welcome Users bot sample! This Introduction card "
"is a great way to introduce your Bot to the user and suggest "
"some things to get them started. We use this opportunity to "
"recommend a few next steps for learning more creating and deploying bots.",
images=[
CardImage(
url="https://aka.ms/bf-welcome-card-image"
)
],
"is a great way to introduce your Bot to the user and suggest "
"some things to get them started. We use this opportunity to "
"recommend a few next steps for learning more creating and deploying bots.",
images=[CardImage(url="https://aka.ms/bf-welcome-card-image")],
buttons=[
CardAction(
type=ActionTypes.open_url,
title="Get an overview",
text="Get an overview",
display_text="Get an overview",
value="https://docs.microsoft.com/en-us/azure/bot-service/?view=azure-bot-service-4.0"
value="https://docs.microsoft.com/en-us/azure/bot-service/?view=azure-bot-service-4.0",
),
CardAction(
type=ActionTypes.open_url,
title="Ask a question",
text="Ask a question",
display_text="Ask a question",
value="https://stackoverflow.com/questions/tagged/botframework"
value="https://stackoverflow.com/questions/tagged/botframework",
),
CardAction(
type=ActionTypes.open_url,
title="Learn how to deploy",
text="Learn how to deploy",
display_text="Learn how to deploy",
value="https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-howto-deploy-azure?view=azure-bot-service-4.0"
)
]
value="https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-howto-deploy-azure?view=azure-bot-service-4.0",
),
],
)

return await turn_context.send_activity(MessageFactory.attachment(CardFactory.hero_card(card)))
return await turn_context.send_activity(
MessageFactory.attachment(CardFactory.hero_card(card))
)
9 changes: 6 additions & 3 deletions samples/05.multi-turn-prompt/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,17 +39,19 @@ async def on_error(context: TurnContext, error: Exception):

# Send a message to the user
await context.send_activity("The bot encountered an error or bug.")
await context.send_activity("To continue to run this bot, please fix the bot source code.")
await context.send_activity(
"To continue to run this bot, please fix the bot source code."
)
# Send a trace activity if we're talking to the Bot Framework Emulator
if context.activity.channel_id == 'emulator':
if context.activity.channel_id == "emulator":
# Create a trace activity that contains the error object
trace_activity = Activity(
label="TurnError",
name="on_turn_error Trace",
timestamp=datetime.utcnow(),
type=ActivityTypes.trace,
value=f"{error}",
value_type="https://www.botframework.com/schemas/error"
value_type="https://www.botframework.com/schemas/error",
)

# Send a trace activity, which will be displayed in Bot Framework Emulator
Expand All @@ -58,6 +60,7 @@ async def on_error(context: TurnContext, error: Exception):
# Clear out state
await CONVERSATION_STATE.delete(context)


# Set the error handler on the Adapter.
# In this case, we want an unbound method, so MethodType is not needed.
ADAPTER.on_turn_error = on_error
Expand Down
22 changes: 11 additions & 11 deletions samples/05.multi-turn-prompt/bots/dialog_bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,21 @@
from botbuilder.dialogs import Dialog
from helpers.dialog_helper import DialogHelper

"""
This Bot implementation can run any type of Dialog. The use of type parameterization is to allows multiple
different bots to be run at different endpoints within the same project. This can be achieved by defining distinct
Controller types each with dependency on distinct Bot types. The ConversationState is used by the Dialog system. The
UserState isn't, however, it might have been used in a Dialog implementation, and the requirement is that all
BotState objects are saved at the end of a turn.
"""


class DialogBot(ActivityHandler):
"""
This Bot implementation can run any type of Dialog. The use of type parameterization is to allows multiple
different bots to be run at different endpoints within the same project. This can be achieved by defining distinct
Controller types each with dependency on distinct Bot types. The ConversationState is used by the Dialog system. The
UserState isn't, however, it might have been used in a Dialog implementation, and the requirement is that all
BotState objects are saved at the end of a turn.
"""

def __init__(
self,
conversation_state: ConversationState,
self,
conversation_state: ConversationState,
user_state: UserState,
dialog: Dialog
dialog: Dialog,
):
if conversation_state is None:
raise TypeError(
Expand Down
Loading